Using count equivalent in MongoDB to find top users with max occurrence


To get the count and top users, use $group along with aggregate() . Let us create a collection with documents −

> db.demo264.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ed441627c0c63e7dba9e")
}
> db.demo264.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ed471627c0c63e7dba9f")
}
> db.demo264.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ed491627c0c63e7dbaa0")
}
> db.demo264.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ed4c1627c0c63e7dbaa1")
}
> db.demo264.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ed4e1627c0c63e7dbaa2")
}
> db.demo264.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ed531627c0c63e7dbaa3")
}

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

> db.demo264.find();

This will produce the following output −

{ "_id" : ObjectId("5e47ed441627c0c63e7dba9e"), "Name" : "Chris" }
{ "_id" : ObjectId("5e47ed471627c0c63e7dba9f"), "Name" : "David" }
{ "_id" : ObjectId("5e47ed491627c0c63e7dbaa0"), "Name" : "Chris" }
{ "_id" : ObjectId("5e47ed4c1627c0c63e7dbaa1"), "Name" : "Bob" }
{ "_id" : ObjectId("5e47ed4e1627c0c63e7dbaa2"), "Name" : "Chris" }
{ "_id" : ObjectId("5e47ed531627c0c63e7dbaa3"), "Name" : "Bob" }

Following is the query to use count equivalent in MongoDB to find top users with max occurrence −

> db.demo264.aggregate(
...   {$group : {_id : "$Name", "count" : {$sum : 1}}},
...   {$sort : {"count" : -1}},
...   {$limit : 5}
...)

This will produce the following output −

{ "_id" : "Chris", "count" : 3 }
{ "_id" : "Bob", "count" : 2 }
{ "_id" : "David", "count" : 1 }

Updated on: 31-Mar-2020

349 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements