[SOLVED] MongoDB : fields are excluded when invoke multiple lookup stages

Issue

This Content is from Stack Overflow. Question asked by dev_tn

enter image description here

Why the fields name and region in collection templatefolders are excluded ?



Solution

Your second $lookup, is overriding the joinDashboard key completely. Since you want joinFolder to be within joinDashboard, you can try nested lookups like this:

db.dashboard.aggregate([
  {
    $lookup: {
      from: "templatefolders",
      let: {
        "boardId": "$_id"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$dashboardId",
                "$$boardId"
              ]
            }
          }
        },
        {
          $lookup: {
            from: "folders",
            let: {
              "folderId": "$folderId"
            },
            pipeline: [
              {
                $match: {
                  $expr: {
                    $eq: [
                      "$_id",
                      "$$folderId"
                    ]
                  }
                }
              },
            ],
            as: "joinFolder"
          },
        },
      ],
      as: "joinDashboard"
    }
  }
])

MongoPlayground link.


This Question was asked in StackOverflow by Mark_STUF and Answered by Charchit Kapoor It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?