如何在Mongo DB中合并文档数组?
要合并,请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" ] ] }
以上是 如何在Mongo DB中合并文档数组? 的全部内容, 来源链接: utcz.com/z/345642.html