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() // 5countDocuments(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 andcursor.count()are deprecated. Replace them with the two above.
The shortcut
Ask "Does my question have a 'where' in it?" Yes → countDocuments with that filter. No, and an approximate total is fine → estimatedDocumentCount.
Out-of-stock books
Has a "where": stock is 0.
countDocuments({ stock: 0 })gives 1.
The trap: calling estimatedDocumentCount({ stock: 0 }) and trusting the answer. It has no filter parameter, so it still reports the whole collection.
Drills
Answer fast — trust the rule.
What does db.books.countDocuments({ genres: "classic" }) return?
Which method counts matches for a filter exactly?
Where does estimatedDocumentCount() get its number?
How many books does countDocuments({ stock: { $lt: 5 } }) count?
Remember
- Filter? countDocuments. Whole collection, fast? estimatedDocumentCount.
- Shortcut: a "where" in the question means countDocuments with that filter.
- Trap:
count()is deprecated, and estimatedDocumentCount ignores any filter you hope to give it.
