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 deprecated count()
  • Use estimatedDocumentCount() for total document count without filters
  • Consider using aggregate() with $match and $count for 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.

Updated on: 2026-03-15T00:13:04+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements