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]
}
Use aggregation framework
db.collection.aggregate(
[
{ $unwind: "$products" },
{ $group: { _id: "$products.gpc", gtin: { $push: "$products.gtin" }}},
{ $project: { gpc: "$_id", gtin: 1, _id: 0 }}
]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With