2

I have two collection one is for storing the menu details and the other is for storing project details The below is the 'allmenu' collection.

{
    "_id" : ObjectId("5ce7454f77af2d1143f84c38"),
    "menu_name" : "mainmenu1",
    "sub_menus" : [ 
        "submenu1",
        "submenu2"
    ]
}

The below is the 'project' collection.

{
    "_id" : ObjectId("5cda19d2e7bb82e771931adb"),
    "project_name" : "p1",
    "sub_menus" : "submenu1",

}
{
    "_id" : ObjectId("5cda19d2e7bb82e771931adb"),
    "project_name" : "p2",
    "sub_menus" : "submenu2",

}

I want the result like below

  {
    "_id" : ObjectId("5ce7454f77af2d1143f84c35"),
    "menu_name" : "mainmenu1",
    "sub_menus" : [
      {"sub_menu_name" : "submenu1",
       "projectData" : [ 
        {
            "project_name" : "p1",            
        }
       ]
      }
    ]  
}

I tried the below query

db.getCollection('allmenu').aggregate([
{"$unwind":"$sub_menus"},
{"$lookup":{
        "from" :"project",
        "localField":"sub_menus",
        "foreignField":"sub_menus",
        "as":"newData"
        }
}])

I checked all the array lookup related questions. But all the questions are different from this.

2
  • What output you are getting with the above aggregation? Commented May 25, 2019 at 11:54
  • Seems very similar to this stackoverflow.com/questions/34967482/… Commented May 25, 2019 at 12:01

1 Answer 1

2

You can use below aggregation

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"
  }}
])

MongoPlayground

Sign up to request clarification or add additional context in comments.

2 Comments

How can i do the group the sub_menu. Its coming multiple times?
i did the grouping. {"$group" : { _id : { 'sub_menus': '$sub_menus'}} } }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.