MongoDB 查询,用于筛选符合条件的所有元素都来自嵌套数组的对象
为此,请使用 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 }
广告