MongoDB Aggregation Sum on Objects in Array -
i've seen lot of answers on how sum properties of objects in arrays within array, i'm trying sum individual properties on object in array across documents. example, given document structure:
{ "id": 1, "stats": [ { "number": 100, "year": 2014 }, { "number": 200, "year": 2015 } ] }, { "id": 2, "stats": [ { "number": 50, "year": 2014 }, { "number": 75, "year": 2015 } ] }
the desired output be:
{ "stats": [ { "number": 150, "year": 2014 }, { "number": 275, "year": 2015 } }
i don't want sum number
property of 2014 , 2015, want sum across 2014 both documents.
db.test.aggregate([ { $unwind: "$stats" }, { $group: { _id:"$stats.year", number:{$sum:"$stats.number"} } }, { $group: { _id: 0, stats:{ $push: {year:"$_id",number:"$number"}} } }, { $project:{stats:1,_id:0} } ])
Comments
Post a Comment