Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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.

The shortcut

Ask "Does my question have a 'where' in it?" Yes → countDocuments with that filter. No, and an approximate total is fine → estimatedDocumentCount.

Three dashboard numbersStep 1 of 4
  1. 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.

quick drill

What does db.books.countDocuments({ genres: "classic" }) return?

quick drill

Which method counts matches for a filter exactly?

quick drill

Where does estimatedDocumentCount() get its number?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhich count?

The shop's dashboard needs two numbers: how many UK-published books there are, and roughly how many books the whole collection holds, refreshed every second. Explain which counting method you would use for each, what each returns on the books collection, and why.