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
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
OUTPUT:
{
{ "result" : [ { "_id" : 3, "title" : [ "Prototype in Javascript" ] }, { "_id" : 2, "title" : [ "AngularJS: Getting started with Directive", "this keyword in Javascript" ] } ], "ok" : 1 }
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Harish Modi
Harish Modi is good in core java, advance java, springBoot. He is ASSOCIATE CONSULTANT - DEVELOPMENT. and Keen to learn new Skills.