要从多个子文档中获取字段,请在$unwind中使用MongoDB聚合。让我们创建一个包含文档的集合-
> db.demo671.insertOne( ... { ... ... "details" : [ ... { ... "id" : "1" ... }, ... { ... CountryName:"US", ... "details1" : [ ... { ... "id" : "1" ... }, ... { ... "id" : "2" ... } ... ] ... }, ... { ... CountryName:"UK", ... "details1" : [ ... { ... "id" : "2" ... }, ... { ... "id" : "1" ... } ... ] ... }, ... { ... CountryName:"AUS", ... "details1" : [ ... { ... "id" : "1" ... } ... ] ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5ea3e5d004263e90dac943e0") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo671.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] }
这是从多个子文档中获取与MongoDB中的条件匹配的字段的查询-
> db.demo671.aggregate([ ... ... {$unwind: '$details'}, ... ... {$match: {'details.details1.id': '1'}}, ... ... {$project: {_id: 0, Country: '$details.CountryName'}} ... ]).pretty()
这将产生以下输出-
{ "Country" : "US" } { "Country" : "UK" } { "Country" : "AUS" }