Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 deprecatedcount()method - Create an index on frequently queried fields for better performance
- The aggregation
$countstage 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.
Advertisements
