MongoDB Counting Documents: countDocuments() vs count() vs itcount()
Learn the right way to count documents in MongoDB using countDocuments(), why the older count() is deprecated, and when to use cursor.itcount() instead.
Counting Documents in MongoDB
countDocuments() (Recommended)
Counts the number of documents matching a filter — this is the modern, recommended way to count.
db.employees.countDocuments()
db.employees.countDocuments({ age: { $gte: 22 } })
count() (Deprecated)
The older count() method still works but prints a deprecation warning — prefer countDocuments() in new code.
db.employees.count()
// DeprecationWarning: Collection.count() is deprecated.
// Use countDocuments or estimatedDocumentCount.
db.employees.find({ age: { $gte: 22 } }).count()
itcount()
A cursor method that counts documents by actually iterating the cursor. It's mainly used when you already have a cursor from find() and want its size directly.
db.employees.find().itcount()
db.employees.find({ age: 24 }).itcount()
Advertisement728 x 90
Common Errors & Troubleshooting
- Seeing a
DeprecationWarningforcount()— this is expected; it still works, but switch tocountDocuments()in new code to avoid it entirely. countDocuments()seeming slow on a huge collection — unlike the old estimated count,countDocuments()performs a real scan matching your filter; for an unfiltered total-row-count on a huge collection,estimatedDocumentCount()is much faster (though less precise, since it reads collection metadata instead of scanning).- Counting after a cursor has already been iterated — calling
itcount()(or any count) on a cursor that's already been fully read returns0, since there's nothing left to iterate; re-run the query to get a fresh cursor.
Key Takeaways
- Use
countDocuments()for new code — it's accurate and not deprecated. count()still runs but MongoDB nudges you towardcountDocuments()instead.itcount()is a cursor-level method, useful when you're already holding a cursor.
Advertisement320 x 100