我有两个集合,一个用于存储菜单详细信息,另一个用于存储项目详细信息 以下是“ allmenu”集合。
{
"_id" : ObjectId("5ce7454f77af2d1143f84c38"),
"menu_name" : "mainmenu1",
"sub_menus" : [
"submenu1",
"submenu2"
]
}
以下是“项目”集合。
{
"_id" : ObjectId("5cda19d2e7bb82e771931adb"),
"project_name" : "p1",
"sub_menus" : "submenu1",
}
{
"_id" : ObjectId("5cda19d2e7bb82e771931adb"),
"project_name" : "p2",
"sub_menus" : "submenu2",
}
我想要下面的结果
{
"_id" : ObjectId("5ce7454f77af2d1143f84c35"),
"menu_name" : "mainmenu1",
"sub_menus" : [
{"sub_menu_name" : "submenu1",
"projectData" : [
{
"project_name" : "p1",
}
]
}
]
}
我尝试了以下查询
db.getCollection('allmenu').aggregate([
{"$unwind":"$sub_menus"},
{"$lookup":{
"from" :"project",
"localField":"sub_menus",
"foreignField":"sub_menus",
"as":"newData"
}
}])
我检查了所有与数组查找有关的问题。但是所有问题与此不同。
答案 0 :(得分:2)
您可以使用以下汇总
db.collection.aggregate([
{ "$lookup": {
"from": "project",
"let": { "sub_menus": "$sub_menus" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$sub_menus", "$$sub_menus"] }}},
{ "$project": {
"projectData": [{ "project_name": "$project_name" }],
"sub_menu_name": "$sub_menus"
}}
],
"as": "sub_menus"
}}
])