How to do Aggregated $lookup in Mongodb on embedded collection of objects

To keep things simple, I would do it like that.

[
  {
    '$addFields': {
      'companies': {
        '$filter': {
          'input': '$companies', 
          'as': 'item', 
          'cond': {
            '$eq': [
              '$$item.primary', true
            ]
          }
        }
      }
    }
  }, {
    '$lookup': {
      'from': 'companies', 
      'localField': 'companies._id', 
      'foreignField': '_id', 
      'as': 'companies'
    }
  }
]

There is probably a way to make it work with the subpipeline like you tried, but apparently I’m not good enough just yet. :sob:
The array isn’t helping. :sweat_smile:

Cheers,
Maxime.

2 Likes