Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb find by query and group

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.

like image 493
UpCat Avatar asked Dec 11 '22 07:12

UpCat


1 Answers

Try this,

db.collection.aggregate(
    { 
        $match : {name : "FooBar"}
    },
    { 
        $group : { 
             _id : "$zone", 
              total : { $sum : 1 } 
        }
    }
);
like image 101
Rishi Rahiman Avatar answered Jan 07 '23 14:01

Rishi Rahiman