Reputation: 155
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 documents. For example, given this 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 would be:
{
"stats": [
{
"number": 150,
"year": 2014
},
{
"number": 275,
"year": 2015
}
}
I don't want to sum the number
property of 2014 and 2015, I want to sum it across 2014 for both documents.
Upvotes: 5
Views: 7934
Reputation: 1107
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}
}
])
Upvotes: 0
Reputation: 1888
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}
} ])
Upvotes: 8