← Back to MongoDB Course | Chapter 3: CRUD — Read | Lesson 7 of 7

Counting documents

countDocuments counts matches accurately and estimatedDocumentCount gives a fast total.

In this page:

  1. Counting documents
Syntax
javascript
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

bash
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
  1. Using the deprecated count
  2. Expecting estimatedDocumentCount to accept a filter
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.