Results, Sorting & Pagination
countDocuments()
Counting matches accurately, and why estimatedDocumentCount is a different question.
countDocuments(filter) runs a real count of matching documents. Use it when the number has to be right — '4,312 completed orders'. The old count() helper is deprecated; do not write it in new code.
db.users.countDocuments({ city: "Bangalore", isActive: true })2
db.orders.estimatedDocumentCount()estimatedDocumentCount() reads collection metadata. It does not take a filter. It can lag slightly on a busy replica. Use it for 'roughly how big is this collection?', not for a badge that says 12 results. countDocuments({}) on a huge collection is a scan (or a fast count if the planner can use an index) — do not put it on every list endpoint next to skip. Offset pagination that also countDocuments the same filter doubles the work.
Interview question
When do you use countDocuments versus estimatedDocumentCount?
countDocuments when the number must match a filter. estimatedDocumentCount when I want a cheap collection size and I am not filtering. I would not use the estimate as a search result count.