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.