How to use group aggregation in Mongdb

Posted By : Harish Modi | 21-Dec-2018

How to use $group(aggregation) in MongoDB

$group allows us to group a collection according to criteria. We can group by fields that exist within the data, or we can group by expressions that create new fields.
Group can treat a collection of documents within the pipeline, and output a new set of documents out the bottom.
with the help of
$group, we can group documents (similar as group By in SQL).
and group using the _id field. It will create a new _id for each group that will be an object containing the grouping criteria.


The simplest group would look like this:

Suppose we have following collection of record:

{ userId:4, name:"Rajesh", title:"NodeJS: Getting started with Directive", rating:5}
{ userId:2, name:"Moham", title:"AngularJS: Getting started with Directive", rating:6}
{ userId:3, name:"Pankaj", title:"Prototype in Javascript", rating:4}
{ userId:2, name:"Sohan", title:"this keyword in Javascript", rating:5}

And now we want to group all the record by userId and rating greater then 4:

 

db.blogs.aggregate([  
   {  
      $match:{  
         rating:{  
            $gt:4
         }
      }
   },
   {  
      $group:{  
         _id:'$userId',
         title:{  
            $push:'$title'
         }
      }
   }
]);


It will return the grouped result of all the blogs with id and title whose rating is greater then 3. Here $match will match the condition, $group groups all the documents by field-name which is provided as _id and $push will add the title into the result.

 

OUTPUT:

{

{
    "result" : [
        {
            "_id" : 3,
            "title" : [
                "Prototype in Javascript"
            ]
        },
        {
            "_id" : 2,
            "title" : [
                "AngularJS: Getting started with Directive",
                "this keyword in Javascript"
            ]
        }
    ],
    "ok" : 1
}

About Author

Author Image
Harish Modi

Harish Modi is good in core java, advance java, springBoot. He is ASSOCIATE CONSULTANT - DEVELOPMENT. and Keen to learn new Skills.

Request for Proposal

Name is required

Comment is required

Sending message..