Search code examples
mongodbmongodb-query

Mongo Unwind child object array to root as plain array


Suppose I have a simple collection like this:

[
  {
    Brands: [ 
                { BID: 1, Prods: [ { PID: 10 }, { PID: 11 } ] },
                { BID: 2, Prods: [ { PID: 20 }, { PID: 21 } ] }
           ]
  },
  {
    Brands: [
                { BID: 3, Prods: [ { PID: 30 }, { PID: 31 }, { PID: 32 } ] }
    ]
  }
]

I want to extract all unique PID from Prods, so the result would be:

[10,11,20,21,30,31,32]

I could get close to this doing this:

db.collection.aggregate([
  {
    $project: {
      "AllProds": {
        "$map": {
          "input": "$Brands.Prods",
          "as": "elem",
          "in": "$$elem.PID"
        }
      }
    }
  }
])

But the result is not a simple array, its a array of objects with the PID inside of it:

[
  {
    "AllProds": [
      [ 10, 11 ],
      [ 20, 21 ]
    ],
    "_id": ObjectId("5a934e000102030405000000")
  },
  {
    "AllProds": [
      [ 30, 31, 32 ]
    ],
    "_id": ObjectId("5a934e000102030405000001")
  }
]

Here is is the playground


Solution

  • You don't exactly require $map here. Just unwind the outer array, then the inner array and group them together

    db.getCollection('SampleCollection').aggregate([
        {
            $unwind:"$Brands"
        },
        {
            $unwind:"$Brands.Prods"
        },
        {
            $group:
            {
                _id:null,
                PIDs: {$push:"$Brands.Prods.PID"}//use $addToSet instead of $push if you do not wish to allow duplicates
            }
        }    
    ])