Grouping data in mongo using stored json data

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 do this to get the gpc value and then the array under the gtins headers? Something like:

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

      

+3


source to share


1 answer


Use aggregation infrastructure



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

      

+2


source







All Articles