请有人指导我如何完成以下操作。我有一个Banks文档,它嵌入了子文档“branches”,后者又嵌入了文档“branchcontacts”。我正在尝试查询其名称为Manager的branchContacts。
我得到的是包含子branchcontacts的完整Bank文档。如何确保仅与“经理”指定的branchContacts作为银行文档的一部分返回。
{
"_id" : ObjectId("558e539941755bca3a966c10"),
"bankCode" : "B001",
"name" : "Progress Bank",
"city" : "Paris",
"branches" : [
{
"name" : "Standard-Gusto",
"address" : "address gusto",
"landLine1" : "343453453",
"mobile1" : "045865964",
"branchcontacts" : [
{
"contactName" : "Daniel",
"designation" : "Manager",
"emailID" : "daniel@prog.com",
"landLine1" : "3453453"
}
{
"contactName" : "Lucy",
"designation" : "Accounant",
"emailID" : "lucy@prog.com",
"landLine1" : "7443456"
}
]
}
{
"name" : "Standard-Pronto",
"address" : "address pronto",
"landLine1" : "763453453",
"mobile1" : "46585964",
"branchContacts" : [
{
"contactName" : "Mary",
"designation" : "Manager",
"emailID" : "mary@prog.com",
"landLine1" : "8453453"
}
{
"contactName" : "Janet",
"designation" : "Accounant",
"emailID" : "janet@prog.com",
"landLine1" : "9943456"
}
]
}
]
}
由于
答案 0 :(得分:0)
请尝试以下方法:
db.collection.aggregate([
{"$unwind" : "$branches"},
{"$unwind": "$branches.branchcontacts"},
{"$match" : {"$branches.branchcontacts.designation" : "Manager"} },
{"$group" : { "_id" :
{ "fid" :"$_id" , "sid" : "$branches.name"} , "bankCode" :
{"$first" : "$bankCode"} ,
"name" : {"$first" : "$name"} , "city" : {"$first" : "$city"},
"branch" : { "name" : {"$first" : "$branches.name"}, "address" :
{"$first" : "$branches.address"}, "contacts" :
{"$push" : "$branches.branchcontacts"} }
} },
{"$group" : {"_id" : "$_id.fid", "bankCode" : {"$first" :
"$bankCode"} ,
"name" : {"$first" : "$name"} , "city" : {"$first" : "$city"},
"branches" : {"$push":"$branch"}
}}
]);