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.

Was it helpful?

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
scroll top