Get the count of a specific value in MongoDB quickly


For faster queries, create an index. To get the count, use count(). Let us create a collection with documents −

> db.demo311.ensureIndex({"Name":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo311.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50cd01f8647eb59e562044")
}
> db.demo311.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50cd05f8647eb59e562045")
}
> db.demo311.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50cd06f8647eb59e562046")
}
> db.demo311.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e50cd0af8647eb59e562047")
}
> db.demo311.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50cd0df8647eb59e562048")
}
> db.demo311.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50cd0ff8647eb59e562049")
}

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

> db.demo311.find();

This will produce the following output −

{ "_id" : ObjectId("5e50cd01f8647eb59e562044"), "Name" : "Chris" }
{ "_id" : ObjectId("5e50cd05f8647eb59e562045"), "Name" : "David" }
{ "_id" : ObjectId("5e50cd06f8647eb59e562046"), "Name" : "David" }
{ "_id" : ObjectId("5e50cd0af8647eb59e562047"), "Name" : "Chris" }
{ "_id" : ObjectId("5e50cd0df8647eb59e562048"), "Name" : "Bob" }
{ "_id" : ObjectId("5e50cd0ff8647eb59e562049"), "Name" : "Chris" }

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

> db.demo311.find({"Name":"Chris"}).count();

This will produce the following output −

3

Updated on: 01-Apr-2020

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements