0

According to docs, db.collection.countDocuments() wraps this:

db.collection.aggregate([
   { $match: <query> },
   { $group: { _id: null, n: { $sum: 1 } } }
])

Even if there is an index, all of the matched docs will be passed into the $group to be counted, no?

If not, how is mongodb able to count the docs without processing all matching docs?

  • Sometimes it processes all of the matching docs. Depending on the filter, some counts can be covered by the index - https://www.mongodb.com/docs/manual/core/query-optimization/#covered-query – user20042973 Feb 14 '23 at 17:36

1 Answers1

1

The MongoDB query planner can make some optimizations.

In that sample aggregation, it can see that no fields are required except for the ones referenced in <query>, so it can add an implicit $project stage to select only those fields.

If those fields and the _id are all included in a single index, there is no need to fetch the documents to execute that query, all the necessary information is available from the index.

Joe
  • 25,000
  • 3
  • 22
  • 44