Mongodb find by query and group
-
21-12-2019 - |
Question
Simple collection:
[
{
_id: '123',
name: 'FooBar',
zone: 'Bas'
},{
_id: '456',
name: 'Alice',
zone: 'Bas'
},{
_id: '789',
name: 'FooBar',
zone: 'Bas'
}
]
First I build a query to find all elements by name:
db.collection.find({name:'FooBar'})
How can I extend this with a group query using aggregation? I would like to group the collection by zone.
Solution
Try this,
db.collection.aggregate(
{
$match : {name : "FooBar"}
},
{
$group : {
_id : "$zone",
total : { $sum : 1 }
}
}
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow