grouping data in mongo using json data stored

197 views Asked by At

This is the data I have in my mongo db:

{
    "_id": ObjectId("556d1c7716efd4a035d8e473"),
    "products": [
        {
            "gtin": 77770000222313,
            "gpc": 10000068
        },
        {
            "gtin": 77770000222312,
            "gpc": 10000068
        }
    ]
}

How do I aggregate this so that I get gpc value and then an array under that of the gtins? Something like:

{
    "gpc":10000068,
    "gtin":[77770000222312,77770000222313]
}
1

There are 1 answers

0
Sede On BEST ANSWER

Use aggregation framework

db.collection.aggregate(
    [
      { $unwind: "$products" },
      { $group: { _id: "$products.gpc", gtin: { $push: "$products.gtin" }}},
      { $project: { gpc: "$_id", gtin: 1, _id: 0 }}
    ]
)