Get the count of a specific value in MongoDB quickly

To get the count of a specific value in MongoDB quickly, use the countDocuments() method with a query filter. For optimal performance, create an index on the field you're counting.

Syntax

db.collection.countDocuments({"field": "value"});

Create Index for Performance

First, create an index on the Name field for faster counting ?

db.demo311.createIndex({"Name": 1});
{
    "createdCollectionAutomatically" : true,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

Sample Data

db.demo311.insertMany([
    {"Name": "Chris"},
    {"Name": "David"},
    {"Name": "David"},
    {"Name": "Chris"},
    {"Name": "Bob"},
    {"Name": "Chris"}
]);

Display Documents

db.demo311.find();
{ "_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" }

Get Count of Specific Value

Count how many documents have Name equal to "Chris" ?

db.demo311.countDocuments({"Name": "Chris"});
3

Alternative Methods

You can also use the aggregation framework for counting ?

db.demo311.aggregate([
    { $match: {"Name": "Chris"} },
    { $count: "total" }
]);
{ "total" : 3 }

Key Points

  • Use countDocuments() instead of deprecated count() method
  • Create an index on frequently queried fields for better performance
  • The aggregation $count stage provides additional flexibility for complex counting operations

Conclusion

Use countDocuments() with proper indexing to efficiently count specific values in MongoDB. This approach provides accurate results and optimal performance for large collections.

Updated on: 2026-03-15T02:22:22+05:30

327 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements