Bussola

countDocuments vs estimatedDocumentCount: Why Counting Is Slow

MongoDB countDocuments is slow on large collections because it is not a lookup: it runs an aggregation that matches documents and counts them one by one. estimatedDocumentCount is fast because it reads a number from collection metadata instead, but it cannot take a filter and the number can be off. The practical rule: use estimatedDocumentCount() for “roughly how big is this collection”, use countDocuments(filter) when you need an exact answer for a filter, and put a limit and maxTimeMS on any count that runs against a big collection. The rest of this article explains why, and shows how to avoid waiting on counts you do not need.

What countDocuments actually does

countDocuments(filter, options) is implemented by the drivers (and by mongosh) as an aggregation. Conceptually it is:

db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $group: { _id: 1, n: { $sum: 1 } } }
])

With the options skip and limit, the driver inserts $skip and $limit stages between the two. So the cost of a count is the cost of the $match: the server must find every matching document, and it cannot answer from a stored total.

That cost depends entirely on what the filter can use:

  • Filter on an indexed field. The server walks an index range (IXSCAN) and counts the matches. Often it does not need to fetch the documents at all. This is fast, but still proportional to the number of matches: counting 40 million matches means visiting 40 million index entries.
  • Filter on an unindexed field. A COLLSCAN reads the whole collection. On a large collection this is the slow case people notice.
  • Empty filter, countDocuments({}). This still goes through the aggregation path and has to traverse the data or an index. It is exact, and it is much slower than the metadata count on a big collection.

You can confirm any of this with explain. See Reading MongoDB explain() in Five Minutes for how to read the stages:

db.orders.explain("executionStats").aggregate([
  { $match: { status: "shipped" } },
  { $group: { _id: 1, n: { $sum: 1 } } }
])

If totalDocsExamined is close to the collection size, the count is a collection scan and an index on the filtered field is the first fix.

What estimatedDocumentCount does

estimatedDocumentCount(options) takes no filter. It asks the server for the collection’s document count from stored metadata, so the answer comes back in roughly constant time regardless of collection size:

db.orders.estimatedDocumentCount()

The main option is maxTimeMS. Because it does not examine documents, nothing about your indexes affects it. (How the driver fetches that metadata can differ between driver and server versions, but the contract is the same: a fast, approximate total.)

The older db.collection.count() is deprecated in favor of these two methods. It could behave like either one depending on whether you passed a query, which is why it was split.

When the estimate is wrong

The metadata count is maintained incrementally as writes happen. It is accurate in normal operation, but the MongoDB documentation lists situations where it can drift:

  • After an unclean shutdown. If a mongod process crashes or is killed without a clean shutdown, the stored count can be inaccurate. Running the validate command on the collection is the documented way to recompute the statistics.
  • On sharded clusters with orphaned documents. After a failed or interrupted chunk migration, documents can exist on a shard that no longer owns them. Counts based on shard metadata may include those orphans. Queries through mongos filter orphans out, so countDocuments returns the correct result where the metadata count may not.

None of this means you should avoid estimatedDocumentCount. It means you should treat it as a size indicator, not as a number for a reconciliation job. If two numbers must agree, use countDocuments.

Choosing between them

Question Use
About how many documents are in this collection? estimatedDocumentCount()
How many documents match this filter, exactly? countDocuments(filter)
Are there at least N matches? countDocuments(filter, { limit: N })
Exact count, but I can wait only a few seconds countDocuments(filter, { maxTimeMS: 3000 })
Exact total of a huge collection, no filter Ask whether you really need it (see below)

Make counting cheap: limit and maxTimeMS

Most interfaces do not need an exact count of a million-row result. They need to know whether there is a next page, or to show “10,000+”. Both can be answered by counting a bounded number of matches.

Cap the count with limit

const CAP = 10000;
const n = db.orders.countDocuments(
  { status: "shipped", total: { $gt: 50 } },
  { limit: CAP + 1 }
);
print(n > CAP ? `${CAP}+` : String(n));

Because $limit stops the pipeline as soon as enough documents have matched, the work is bounded by CAP + 1 matches rather than by the total number of matches. Counting one more than the cap is what lets you distinguish exactly 10,000 from more than 10,000.

This is a big win when the filter is supported by an index. It helps less when the filter is unindexed and matches are rare: the scan still has to read documents until it finds enough matches, which may mean reading most of the collection.

Put a time limit on it

maxTimeMS makes the server abort the operation with an error if it runs too long, instead of letting it hold resources:

try {
  db.orders.countDocuments({ customerId: "c_1042" }, { maxTimeMS: 2000 })
} catch (e) {
  // MaxTimeMSExpired: show "count unavailable" instead of blocking
}

Set it on counts that sit behind a UI, a dashboard or an interactive session. A count that times out at two seconds and shows “unavailable” is usually a better experience than a spinner that lasts a minute, and it protects the cluster from someone repeatedly launching the same expensive scan. This matters most on a mobile connection, where a weak signal already makes waiting unpredictable.

Force a good index with hint

If you know which index suits the filter and the planner picks a worse one, countDocuments accepts hint:

db.orders.countDocuments(
  { status: "shipped" },
  { hint: { status: 1, createdAt: -1 } }
)

Use this sparingly. If the hinted index is later dropped or renamed, the command fails, so you trade flexibility for predictability.

Alternatives to counting at all

Before optimizing a count, ask whether the number is needed:

  • Pagination. Fetch pageSize + 1 documents; if you get the extra one, there is a next page. No count required. Prefer range-based paging on an indexed field over skip for deep pages.
  • Dashboards. Maintain a counter document updated with $inc when records change, or compute totals on a schedule and store them. Reads become constant time; you accept slight staleness or extra write work.
  • Existence checks. If you only need “is there any match”, use findOne(filter, { _id: 1 }) or find(filter).limit(1). That stops at the first hit.
  • Grouped counts. If you want counts per status, one $group pass over the data is far cheaper than running countDocuments once per value:
db.orders.aggregate([
  { $group: { _id: "$status", n: { $sum: 1 } } },
  { $sort: { n: -1 } }
])

Counting from a phone

If you check numbers during an incident from a mobile client, the same rules apply with higher stakes: a slow count over a cellular connection is slow for you and for the cluster. Bussola shows counts alongside query results and runs operations with timeouts that can be cancelled, but the sensible habit is the same as on a desktop: use an indexed filter, and prefer a bounded count when you only need an order of magnitude. See the on-call checklist for other quick checks that stay cheap on production.

Summary

  • countDocuments is an aggregation ($match + $group): exact, filterable, and as slow as its $match.
  • estimatedDocumentCount reads metadata: fast, no filter, and potentially inaccurate after an unclean shutdown or with orphaned documents on a sharded cluster.
  • Index the fields you filter on, and verify with explain("executionStats").
  • Use limit to turn exact totals into “N+” and maxTimeMS so counts cannot run unbounded.
  • Often the best count is the one you do not run: paginate with pageSize + 1, keep counters, or check existence with limit(1).
mongodbperformancecountaggregationmongosh

Bussola is a free MongoDB client for iPhone: query, edit and aggregate over a direct connection, with no backend.

Coming soon to the App Store