在 MongoDB 中按 MongoDB 中的子文档过滤子文档?
为此,请将 aggregate() 与 $unwind 结合使用。让我们创建一个包含文档的集合 -
> db.demo583.insert([ ... { ... "details1" : [ ... { ... "details2" : [ ... { ... "isMarried" : true, ... "Name" : "Chris" ... }, ... { ... "isMarried" : true, ... "Name" : "Bob" ... } ... ] ... }, ... { ... "details2" : [ ... { ... "isMarried" : false, ... "Name" : "Chris" ... }, ... { ... "isMarried" : true, ... "Name" : "Mike" ... } ... ] ... } ... ] ... } ... ]); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
在 find() 方法的帮助下显示集合中的所有文档 -
> db.demo583.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : [ { "details2" : [ { "isMarried" : true, "Name" : "Chris" }, { "isMarried" : true, "Name" : "Bob" } ] }, { "details2" : [ { "isMarried" : false, "Name" : "Chris" }, { "isMarried" : true, "Name" : "Mike" } ] } ] }
以下是按子文档过滤子文档的查询 -
> var q= [ ... { ... "$match": { ... "details1.details2.isMarried": true, ... "details1.details2.Name": "Chris" ... } ... }, ... { ... "$unwind": "$details1" ... }, ... { ... "$unwind": "$details1.details2" ... }, ... { ... "$match": { ... "details1.details2.isMarried": true, ... "details1.details2.Name": "Chris" ... } ... } ... ]; > db.demo583.aggregate(q).pretty();
这将生成以下输出 -
{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : { "details2" : { "isMarried" : true, "Name" : "Chris" } } }
广告