Skip to the workspace
Pebellslearn by building
Collections & Methods  ›  Lesson

Counting Documents

Counting Documents 12 mincountDocuments counts the documents matching a filter exactly, while estimatedDocumentCount reads collection metadata to give a fast total with no filter.

mongodb / Counting Documents

Explore each scene at your own pace.

01 · The rule

The rule

Counting Documents

"How many books are out of stock?" and "How big is the catalogue?" sound like the same kind of question. MongoDB answers them with two different methods, because one needs to look at documents and the other can simply read a number the collection keeps about itself.

The rule

Filter? countDocuments. Whole collection, fast? estimatedDocumentCount.

db.books.countDocuments({ stock: 0 })                     // 1  (Neuromancer)
db.books.countDocuments({ "publisher.country": "US" })    // 3  (Dune, Neuromancer, Circe)
db.books.countDocuments({})                               // 5
db.books.estimatedDocumentCount()                         // 5
  • countDocuments(filter) finds the matching documents and counts them. Always exact, accepts any filter, and speeds up when an index covers the filter. It also accepts options such as { limit: 100 } to stop counting early.
  • estimatedDocumentCount() takes no filter. It reads the count from the collection's metadata, so it is almost instant even on millions of documents. In rare situations, such as after an unclean shutdown or with orphaned documents in a sharded cluster, it can be slightly off.
  • The older count() method and cursor.count() are deprecated. Replace them with the two above.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.