How can I aggregate collection and group by field count in MongoDB?


In MongoDB aggregate(), use $group and aggregate collection. Let us create a collection with documents −

> db.demo616.insertOne({"details":{"Name":"Chris","Age":21}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e99bfac65492f6c60d00283")
}
> db.demo616.insertOne({"details":{"Name":"Chris","Age":22}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e99bfb065492f6c60d00284")
}
> db.demo616.insertOne({"details":{"Name":"Bob","Age":23}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e99bfb865492f6c60d00285")
}
> db.demo616.insertOne({"details":{"Name":"Sam","Age":21}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e99bfbd65492f6c60d00286")
}
> db.demo616.insertOne({"details":{"Name":"Chris","Age":24}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e99bfc165492f6c60d00287")
}

Display all documents from a collection with the help of find() method −

> db.demo616.find();

This will produce the following output −

{ "_id" : ObjectId("5e99bfac65492f6c60d00283"), "details" : { "Name" : "Chris", "Age" : 21 } }
{ "_id" : ObjectId("5e99bfb065492f6c60d00284"), "details" : { "Name" : "Chris", "Age" : 22 } }
{ "_id" : ObjectId("5e99bfb865492f6c60d00285"), "details" : { "Name" : "Bob", "Age" : 23 } }
{ "_id" : ObjectId("5e99bfbd65492f6c60d00286"), "details" : { "Name" : "Sam", "Age" : 21 } }
{ "_id" : ObjectId("5e99bfc165492f6c60d00287"), "details" : { "Name" : "Chris", "Age" : 24 } }

Following is the query to aggregate collection and group by field count −

> db.demo616.aggregate(
... [
...    {
...       $group:{_id:"$details.Name",Total:{$sum:1}}}
... ]
... );

This will produce the following output −

{ "_id" : "Sam", "Total" : 1 }
{ "_id" : "Bob", "Total" : 1 }
{ "_id" : "Chris", "Total" : 3 }

Updated on: 12-May-2020

547 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements