要将多个数组聚合为一个数组,请在MongoDB中使用$project。让我们创建一个包含文档的集合-
> db.demo119.insertOne( ... { ... "_id": 101, ... "WebDetails": [ ... { ... "ImagePath": "/all/image1", ... "isCorrect": "false" ... }, ... { ... "ImagePath": "/all/image2", ... "isCorrect": "true" ... } ... ], ... "ClientDetails": [ ... { ... "Name": "Chris", ... "isCorrect": "false" ... }, ... { ... "Name": "David", ... "isCorrect": "true" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo119.find();
这将产生以下输出-
{ "_id" : 101, "WebDetails" : [ { "ImagePath" : "/all/image1", "isCorrect" : "false" }, { "ImagePath" : "/all/image2", "isCorrect" : "true" } ], "ClientDetails" : [ { "Name" : "Chris", "isCorrect" : "false" }, { "Name" : "David", "isCorrect" : "true" } ] }
以下是使用MongoDB将多个阵列聚合到单个阵列中的查询-
> > db.demo119.aggregate([ ... { "$project": { ... "AllDetails": { ... "$filter": { ... "input": { ... "$setUnion": [ ... { "$ifNull": [ "$WebDetails", [] ] }, ... { "$ifNull": [ "$ClientDetails", [] ] } ... ] ... }, ... "as": "out", ... "cond": { "$eq": [ "$$out.isCorrect", "false" ] } ... } ... } ... }}, ... { "$match": { "AllDetails.0": { "$exists": true } } } ... ])
这将产生以下输出-
{ "_id" : 101, "AllDetails" : [ { "ImagePath" : "/all/image1", "isCorrect" : "false" }, { "Name" : "Chris", "isCorrect" : "false" } ] }