从多个子文档中获取与MongoDB中的条件匹配的字段?
要从多个子文档中获取字段,请在$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" }热门推荐
10 宝宝生病简短祝福语大全
11 毕业祝福语简短给同学
12 简短古文生日祝福语
13 要过年了祝福语简短
14 班级群毕业祝福语简短
15 诗意新婚祝福语高级简短
16 新年探亲祝福语简短精辟
17 双节祝福语简短英文
18 婚礼仪式祝福语简短