Get the count of a specific value in MongoDB


To get the count of a specific value in MongoDB, use aggregate(). Let us create a collection with documents −

> db.demo210.insertOne(
...   {
...      details: [
...         {
...            ClientName: "Robert"
...         },
...         {
...
...            lientName: "John Doe"
...         },
...         {
...
...            ClientName: "Robert"
...         },
...         {
...
...            ClientName: "Robert"
...         },
...         {
...
...            ClientName: "David Miller"
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d99ab03d395bdc21346f9")
}

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

> db.demo210.find();

This will produce the following output −

{ "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "details" : [ { "ClientName" : "Robert" }, { "ClientName" : "John Doe" }, { "ClientName" : "Robert" }, { "ClientName" : "Robert" }, { "ClientName" : "David Miller" } ] }

Following is the query to get the count of a specific value −

> db.demo210.aggregate([
...   { "$match" : { "details.ClientName" : "Robert" } },
...   { "$unwind" : "$details" },
...   { "$match" : { "details.ClientName" : "Robert" } },
...   { "$group" : { "_id" : "$_id", "Size" : { "$sum" : 1 } } },
...   { "$match" : { "Size" : { "$gte" : 2 } } }
...]);

This will produce the following output −

{ "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "Size" : 3 }

Updated on: 27-Mar-2020

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements