I\'ve seen a lot of answers on how to sum properties of objects in arrays within the array, but I\'m trying to sum individual properties on an object in an array across docu
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}
} ])
This will give you the desired output
db.getCollection('yourcollection').aggregate([
{ $unwind: "$stats" },
{
$group: {
_id: "$stats.year",
number:{$sum:"$stats.number"}
}
},
{
$group: {
_id: null,
stats:{ $push: {year:"$_id",number:"$number"}}
}
},
{
$project:{stats:1,_id:0}
}
])