Group By in MongoDB(with $group)

04 / Oct / 2013 by Amit Kumar 0 comments

MongoDB provides a rich set of aggregation. $group is one of them, with the help of $group, we can group documents (similar as group By in SQL). Lets understand by an example:

Suppose we have following collection of blogs:

{ userId:1, name:"Suroor", title:"AngularJS: Getting started with Directive", rating:3}
{ userId:2, name:"Amit", title:"AngularJS: Getting started with Directive", rating:5}
{ userId:3, name:"PI", title:"Prototype in Javascript", rating:4}
{ userId:2, name:"Amit", title:"this keyword in Javascript", rating:5}

And now we want to group all the blogs by userId and rating greater then 3:

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

This will return 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 result.

OUTPUT:

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

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

FOUND THIS USEFUL? SHARE IT

Leave a comment -