Aggregate help - using lookup for each document in a nested array

I am trying to formulate a pipeline that will do a $lookup for each item in an array of sub-documents.

so for each category.attribute i need to lookup the matching attribute document from the attributes collection.

categories collection

[
    { 
      _id: ObjectId("123456"),
      name: "Foo"
      attributes: [
          {
          required: true,
          attribute: ObjectId("098765")
          },
           {
          required: true,
          attribute: ObjectId("34509")
          },
      ]
    }
]

attributes collection

[
    {
      _id: ObjectId("098765"),
     key: "bar"
    },
        {
      _id: ObjectId("34509"),
     key: "baz"
    }
]

Hi!

you probably need to use $unwind on the array so on the next stage you’ll use $lookup for each element
4 things you should keep in mind during aggregations:

  1. filter as much as you can with $match at the beginning of the pipeline
  2. $project only the necessary fields before unwinding the lookup (save memory)
  3. make sure you are not doing a lookup to a massive amount of documents so it will have performance implications
  4. if it’s a recurring query then you should consider storing all of this data together in the same collection.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.