为此,请使用aggregate()
。首先让我们创建一个包含文档的集合-
> db.demo418.insertOne( ... { ... "details":[ ... { ... "CountryName":"US", ... "Marks":45 ... }, ... { ... "CountryName":"US", ... "Marks":56 ... }, ... ... ], ... "Name":"John" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e724324b912067e57771ae6") } > db.demo418.insertOne( ... { ... "details":[ ... { ... "CountryName":"US", ... "Marks":78 ... }, ... { ... "CountryName":"UK", ... "Marks":97 ... }, ... ... ], ... "Name":"Mike" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e724325b912067e57771ae7") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo418.find();
这将产生以下输出-
{ "_id" : ObjectId("5e724324b912067e57771ae6"), "details" : [ { "CountryName" : "US", "Marks" : 45 }, { "CountryName" : "US", "Marks" : 56 } ], "Name" : "John" } { "_id" : ObjectId("5e724325b912067e57771ae7"), "details" : [ { "CountryName" : "US", "Marks" : 78 }, { "CountryName" : "UK", "Marks" : 97 } ], "Name" : "Mike" }
以下是过滤对象的查询,其中嵌套数组中的所有元素均符合条件-
> db.demo418.aggregate([ ... {$unwind:"$details"}, ... { $group: { ... _id: '$_id', ... details : { $first: '$details' }, ... alldetails: { $sum: 1 }, ... alldetailsmatch: { $sum: { $cond: [ { $eq: [ '$details.CountryName', "US" ] }, 1, 0 ] } }, ... Name: { $first: '$Name' } ... }}, ... { $project: { ... _id: 1, ... Name: 1, ... details: 1, ... arrayValue: { $cond: [ { $eq: [ '$alldetails', '$alldetailsmatch' ] }, 1, 0 ] } ... }}, ... { $match: { 'arrayValue' : 1 } } ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e724324b912067e57771ae6"), "details" : { "CountryName" : "US", "Marks" : 45 }, "Name" : "John", "arrayValue" : 1 }