Counting documents
countDocuments counts matches accurately and estimatedDocumentCount gives a fast total.
In this page:
Syntax
db.collection_name.countDocuments(filter)
db.collection_name.estimatedDocumentCount()
Counting documents
countDocuments(filter) runs the query and returns an exact count, using indexes when it can. estimatedDocumentCount() reads collection metadata for a very fast approximate total and takes no filter. distinct(field) returns the set of unique values.
Note:
Use estimatedDocumentCount for dashboards over huge collections.
Example: Counting documents
test> db.users.insertMany([
... { _id: 1, city: "Oslo", active: true }, { _id: 2, city: "Oslo", active: false },
... { _id: 3, city: "Rome", active: true }, { _id: 4, city: "Lima", active: true }
... ])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.users.countDocuments()
4
test> db.users.countDocuments({ active: true })
3
test> db.users.estimatedDocumentCount()
4
test> db.users.distinct("city")
[ 'Oslo', 'Rome', 'Lima' ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using the deprecated count
- Expecting estimatedDocumentCount to accept a filter
- Counting by fetching all documents
Chapter Summary
- countDocuments(filter) is exact
- estimatedDocumentCount is fast and unfiltered
- distinct lists unique values
- Do not count by fetching everything
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: