Hasdfa
Hasdfa

Reputation: 166

Group by objects in inner array (mongodb aggregation)

I have docs like:

{
    "products": [
        {
           "uid": "aside-11kka-asdm12-asdjl"
           "price": 123,
           "count": 123
        }
    ]
}

And I want to group this into array of products, using aggregation (product uids can be repeated in another object)

Upvotes: 2

Views: 2065

Answers (1)

Ashh
Ashh

Reputation: 46491

You need to $unwind first in order to group nested array

db.collection.aggregate([
  {
    "$unwind": "$products"
  },
  {
    $group: {
      "_id": "$products.uid",
      "count": {
        $push: "$products.count"
      },
      "price": {
        $push: "$products.price"
      }
    }
  }
])

Upvotes: 3

Related Questions