Reputation: 43
I'm using Mongoose with NodeJS (typescript). I'm trying to sum the count per location. Example output :
[
{ name : "Bronx", count : 6 },
{ name : "Brooklyn", count : 6 },
{ name : "Manhattan", count : 6 },
{ name : "Queens", count : 6 }
]
Current data model:
data:
[
{
"news": {
"_id": "5c7615a4ef5238a6c47cbcb9",
"locations": [
{
"_id": "5c7615a4ef5238a6c47cbcc6",
"id": "1",
"name": "Manhattan",
"children": [
{
"_id": "5c7615a4ef5238a6c47cbcc8",
"count": 3
},
{
"_id": "5c7615a4ef5238a6c47cbcc7",
"count": 2
}
]
}
]
}
},
{
....
}
]
The last query that I build was :
DataModel.aggregate([
{ "$unwind": "$data.news.locations" },
{
"$group": {
"_id": "$data.news.locations",
"count": { "$sum": "$$data.news.locations.zipcodes.count" }
}
}]).exec(function(err, results){
if (err) throw err;
console.log(JSON.stringify(results, null, 4));
});
But I'm new handle queries in MongoDB with Mongoose, so any help I really appreciate. thanks.
Upvotes: 1
Views: 71
Reputation: 151220
You were kind of close, just a few changes:
DataModel.aggregate([
// Each array needs $unwind separately
{ "$unwind": "$data" },
// And then down to the next one
{ "$unwind": "$data.news.locations" },
// Group on the grouping key
{ "$group": {
"_id": "$data.news.locations.name",
"count": { "$sum": { "$sum": "$data.news.locations.children.count" } }
}}
],(err,results) => {
// remaining handling
})
So since you have arrays inside an array and you want to get down to the "name"
property inside the "locations"
you need to $unwind
to that point. You must $unwind
each array level separately.
Technically there is still the children
array as well, but $sum
can be used to "sum an array of values" as well as "accumulate for a grouping key". Hence the $sum: { $sum
statement within the $group
.
Returns:
{ "_id" : "Manhattan", "count" : 5 }
From the detail supplied in the question.
Upvotes: 1