为此,请在MongoDB中使用aggregate()。让我们创建一个包含文档的集合-
> db.demo736.insertOne( ... { ... "_id": "101", ... "details1": [ ... { ... "details2": [ ... { ... "details3": { ... "Name": "John" ... } ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : "101" } > db.demo736.insertOne( ... { ... "_id": "102", ... "details1": [ ... { ... "details2": [ ... { ... "details3": { ... "Name": "Robert" ... } ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : "102" }
在find()方法的帮助下显示集合中的所有文档-
> db.demo736.find();
这将产生以下输出-
{ "_id" : "101", "details1" : [ { "details2" : [ { "details3" : { "Name" : "John" } } ] } ] } { "_id" : "102", "details1" : [ { "details2" : [ { "details3" : { "Name" : "Robert" } } ] } ] }
以下是在MongoDB中过滤嵌入式文档数组(3个级别)的查询-
> db.demo736.aggregate([ ... { ... "$unwind": "$details1" ... }, ... { ... "$unwind": "$details1.details2" ... }, ... { ... "$match": { ... "details1.details2.details3.Name": "Robert" ... } ... }, ... { ... $project: { ... _id: 0, ... Name: "$details1.details2.details3", ... } ... } ... ])
这将产生以下输出-
{ "Name" : { "Name" : "Robert" } }