Search code examples
mongodbmongoosemongodb-queryaggregation-frameworkmongoose-populate

Populate fields lookup of an obj array


Inside Element I have an array of associations, these associations are a collection.

This collection is obj made up of many keys, among these keys there are elements that refer to other collections (obj, obj2) I would like to populate these two collections.

But I'm not able to understand how it can do, even to try to do as few operations as possible.

From what I understand maybe you need to use $unwind.

Element:

{
_id: "",
element: "",
associations: [],
updatedAt: "",
createdAt: ""
}

Association:

{
_id: "",
code: "",
obj: "5s5s55s5d555dff", //populate - Schema.Types.ObjectId - ref: 'objGroup'
obj2: "5f5e5e5e5d5d5d5", //populate - Schema.Types.ObjectId - ref: 'obj2Group'
updatedAt: "",
createdAt: ""
}

In element:

aggregate.push({
    $lookup: {
      from: 'associations',
      let: { cId: '$_id' },
      pipeline: [
        { $match: { $expr: { $eq: ['$code', '$$cId'] } } },
        { $match: { $or: getTimeRange(from, to) } }
      ],
      as: 'associations'
    }
  })

Solution

  • You can use nested lookup inside lookup pipeline,

    db.element.aggregate([
      {
        $lookup: {
          from: "associations",
          let: { cId: "$_id" },
          pipeline: [
            { $match: { $expr: { $eq: ["$code", "$$cId"] } } },
            { $match: { $or: getTimeRange(from, to) } },
            {
              $lookup: {
                from: "objCollection",
                localField: "obj",
                foreignField: "_id",
                as: "obj"
              }
            },
            { $unwind: "$obj" },
            {
              $lookup: {
                from: "obj2Collection",
                localField: "obj2",
                foreignField: "_id",
                as: "obj2"
              }
            },
            { $unwind: "$obj2" }
          ],
          as: "associations"
        }
      }
    ])