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
MongoDB 'count()' is very slow. How do we work around with it?
MongoDB's count() method can be slow on large collections because it performs a collection scan. To improve performance, create indexes on fields used in count queries and consider alternative methods like countDocuments() or estimatedDocumentCount().
Syntax
// Create index to speed up count operations
db.collection.createIndex({ "fieldName": 1 });
// Count with index support
db.collection.countDocuments({ "fieldName": "value" });
// Fast estimated count (no query filter)
db.collection.estimatedDocumentCount();
Sample Data
db.countPerformanceDemo.insertMany([
{ "StudentName": "John", "StudentCountryName": "US" },
{ "StudentName": "Mike", "StudentCountryName": "UK" },
{ "StudentName": "David", "StudentCountryName": "AUS" },
{ "StudentName": "Carol", "StudentCountryName": "US" },
{ "StudentName": "Bob", "StudentCountryName": "UK" },
{ "StudentName": "David", "StudentCountryName": "UK" },
{ "StudentName": "David", "StudentCountryName": "US" }
]);
Method 1: Using Index with countDocuments() (Recommended)
Create an index on the field you'll count by ?
db.countPerformanceDemo.createIndex({ "StudentName": 1 });
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Now count documents using the indexed field ?
db.countPerformanceDemo.countDocuments({ "StudentName": "David" });
3
Method 2: Using estimatedDocumentCount() for Total Count
For counting all documents without filters, use estimatedDocumentCount() which is much faster ?
db.countPerformanceDemo.estimatedDocumentCount();
7
Key Performance Tips
- Always create indexes on fields used in count queries
- Use
countDocuments()instead of deprecatedcount() - Use
estimatedDocumentCount()for total document count without filters - Consider using
aggregate()with$matchand$countfor complex queries
Conclusion
Speed up MongoDB count operations by creating indexes on query fields and using countDocuments() or estimatedDocumentCount(). Proper indexing transforms slow collection scans into fast index lookups.
Advertisements
