Aggregate with multiple lookup and pipeline return only the last element

31 views
Skip to first unread message

Savano Miatama

unread,
May 28, 2021, 4:57:22 AM5/28/21
to Mongoose Node.JS ODM

I try below code, it's working to lookup value from other collection. But why it only return the last element.

If I omitted the unwind function, It does return all result from the model, but the second lookup will not working as the first lookup return arrays.

My objective is to look up folder that include the model id which represented in templatefolders collection.


I came from front end background. I hope my question is not a silly one

const result = await this.dashboardModel
      .aggregate([{ $match: filter }])
      .lookup({
        from: 'templatefolders',
        as: 'template',
        let: { id: '$_id' },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  {
                    $eq: ['$dashboardId', '$$id'],
                  },
                  {
                    $eq: ['$deletedAt', null],
                  },
                ],
              },
            },
          },
          {
            $project: {
              _id: 1,
              folderId: 1,
            },
          },
        ],
      })
      .unwind('template')
      .lookup({
        from: 'folders',
        as: 'folder',
        let: { folderId: '$template.folderId' },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  {
                    $eq: ['$_id', '$$folderId'],
                  },
                  {
                    $eq: ['$deletedAt', null],
                  },
                ],
              },
            },
          },
          {
            $project: {
              _id: 1,
              name: 1,
            },
          },
        ],
      })
      .unwind('folder')
      .exec();
    return result;

but the result is only one element

[
  {
    ...(parent field)
    "template": {
      "_id": "60ab22b03b39e40012b7cc4a",
      "folderId": "60ab080b3b39e40012b7cc41"
    },
    "folder": {
      "_id": "60ab080b3b39e40012b7cc41",
      "name": "Folder 1"
    }
  }
]

Here are the sample data.

dashboard: [{
  _id: dashboard1
}]

templatefolders: [{
  dashboardId: dashboard1,
  folderId: folder123
}]

folders: [{
  _id: folder123
}]
Reply all
Reply to author
Forward
0 new messages