Get the count of a specific value in MongoDB

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 27-Mar-2020 11:04:51
Advertisements