我有三个集合,其中包含如下所示的数据,
客户集合
{
"_id" : ObjectId("5a058e316803fafd127b23c9"),
"client_name" : "client A",
"client_status" : "A"
}
{
"_id" : ObjectId("5a058e316803fafd127b23cb"),
"client_name" : "client B",
"client_status" : "A"
}
泳池收藏
{
"_id" : ObjectId("5a0e76f66803fa530a7b23d4"),
"pool_name" : "pool A",
"pool_status" : "A",
"client_id" : ObjectId("5a058e316803fafd127b23c9"),
"schools" : [
ObjectId("5a0e742b6803faa6097b2462"),
ObjectId("5a0e742b6803faa6097b2464")
]
}
{
"_id" : ObjectId("5a0e76f76803fa530a7b2402"),
"pool_name" : "pool B",
"pool_status" : "A",
"client_id" : ObjectId("5a058e316803fafd127b23c9"),
"schools" : [
ObjectId("5a0e742b6803faa6097b2463")
]
}
{
"_id" : ObjectId("5a0e76f76803fa530a7b23f6"),
"pool_name" : "pool C",
"pool_status" : "A",
"client_id" : ObjectId("5a058e316803fafd127b23cb"),
"schools" : [
ObjectId("5a7aa1476803fa1f117b23d1")
]
}
学校收藏
{
"_id" : ObjectId("5a0e742b6803faa6097b2462"),
"school_name" : "School A",
"school_status" : "A"
}
{
"_id" : ObjectId("5a0e742b6803faa6097b2463"),
"school_name" : "School B",
"school_status" : "A"
}
{
"_id" : ObjectId("5a0e742b6803faa6097b2464"),
"school_name" : "School C",
"school_status" : "A"
}
{
"_id" : ObjectId("5a7aa1476803fa1f117b23d1"),
"school_name" : "School D",
"school_status" : "A"
}
从这个集合中,我需要为波纹管这样的客户获取泳池学校的列表。
**Output**
{
"_id" : ObjectId("5a058e316803fafd127b23c9"),
"client_name" : "client A",
"client_status" : "A"
"pools" : [
{
"_id" : ObjectId("5a0e76f66803fa530a7b23d4"),
"pool_name" : "pool A",
"pool_status" : "A",
'schools' => [
{
"_id" : ObjectId("5a0e742b6803faa6097b2462"),
"school_name" : "School A",
"school_status" : "A"
},
{
"_id" : ObjectId("5a0e742b6803faa6097b2464"),
"school_name" : "School C",
"school_status" : "A"
},
]
},
{
"_id" : ObjectId("5a0e76f76803fa530a7b2402"),
"pool_name" : "pool B",
"pool_status" : "A",
"schools" : [
{
"_id" : ObjectId("5a0e742b6803faa6097b2463"),
"school_name" : "School B",
"school_status" : "A"
}
]
}
]
},
{
"_id" : ObjectId("5a058e316803fafd127b23cb"),
"client_name" : "client B",
"client_status" : "A"
"pools" : [
{
"_id" : ObjectId("5a0e76f76803fa530a7b23f6"),
"pool_name" : "pool C",
"pool_status" : "A",
"schools" : [
{
"_id" : ObjectId("5a7aa1476803fa1f117b23d1"),
"school_name" : "School D",
"school_status" : "A"
}
]
}
]
}
答案 0 :(得分:1)
您可以尝试以下汇总
Mongodb 3.6引入了嵌套$lookup
管道...因此,您无需像上面那样使用另一个$lookup
阶段...您可以使用嵌套$lookup
管道这里
Client.aggregate([
{ "$match": { 'client_status': 'A' } },
{ "$lookup": {
"from": Pool.collection.name,
"let": { "client_id": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$client_id", "$$client_id" ] } } },
{ "$addFields": {
"schools": {
"$ifNull": ["$schools", []]
}
}}
{ "$lookup": {
"from": Schools.collection.name,
"let": { "schools": "$schools" },
"pipeline": [
{ "$match": { "$expr": { "$in": [ "$_id", "$$schools" ] } } }
],
"as": "schools"
}}
],
"as": "pools"
}}
])
有关冗长的解释,您可以浏览$lookup multiple levels without $unwind?