How to flat nested arrays in Mongo?

Viewed 29

I have two collections which I aggregate together using the $lookup.

After the aggregation my $project results look like that-

{
  _id: ObjectId('123456789123345678912345'),
  key1: 'value1',
  key2: 'value2',
  key3: [
    ['val1', 'val2'],
    ['val1', 'val3'],
    ['val2', 'val4']
  ]
}

I would like to flat and merge all the nested arrays under key3, or in other words to get the following result-

{
  _id: ObjectId('123456789123345678912345'),
  key1: 'value1',
  key2: 'value2',
  key3: ['val1', 'val2', 'val3', 'val4']
}

Note: the key3 is imported from the lookup collection which I merge into the original document, which contains key1 and key2.

1 Answers
  • $reduce to iterate loop of key3, set initial value as empty array
  • $setUnion to get unique value from inivialValue of reduce and current array
db.collection.aggregate([
  {
    $addFields: {
      key3: {
        $reduce: {
          input: "$key3",
          initialValue: [],
          in: { $setUnion: ["$$value", "$$this"] }
        }
      }
    }
  }
])

Playground

Related