Skip to content

Results, Sorting & Pagination

countDocuments()

Counting matches accurately, and why estimatedDocumentCount is a different question.

BeginnerAbout 3 minutes

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 })
How many Bangalore users are active?
2
db.orders.estimatedDocumentCount()
Fast, approximate, ignores your filter

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?

Think about it first.