如何在 MongoDB 中合并文档数组?
要进行合并,请使用 aggregate() 以及 $PUSH。我们用文档创建一个集合 −
> db.demo64.insertOne({"Subjects":["MySQL","MongoDB","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e28762bcfb11e5c34d89936") } > db.demo64.insertOne({"Subjects":["Oracle","Spring","Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e28763fcfb11e5c34d89937") }
通过 find() 方法显示集合中的所有文档 −
> db.demo64.find();
这会生成以下输出 −
{ "_id" : ObjectId("5e28762bcfb11e5c34d89936"), "Subjects" : [ "MySQL", "MongoDB", "Java" ] } { "_id" : ObjectId("5e28763fcfb11e5c34d89937"), "Subjects" : [ "Oracle", "Spring", "Python" ] }
以下是 MongoDB 中合并文档数组的查询 −
> db.demo64.aggregate([ ... { "$group": { ... "_id": null, ... "Subjects": { "$push": "$Subjects" } ... }}, ... { "$project": { "_id": 0 }} ... ]);
这会生成以下输出 −
{ "Subjects" : [ [ "MySQL", "MongoDB", "Java" ], [ "Oracle", "Spring", "Python" ] ] }
广告