Skip to content

Troubleshooting guide

MongoDB slow queries: how to find and fix them

Slow MongoDB queries usually mean a collection scan or an index that does not fit the query. The profiler and `explain` show which.

3 min read11 sectionsUpdated

On this page

Key points

  • COLLSCAN is the main warning sign.
  • Compare docsExamined with nReturned.
  • Follow Equality, Sort, Range when ordering compound index fields.
  • The profiler has overhead, so keep it narrow.

How to think about it

An efficient query examines about as many documents as it returns. If it examines a million to return ten, there is either no suitable index, or the index order does not match. Slow operations above 100 ms are written to the log by default.

Common causes

  • No index on the filter fields.
  • In-memory sorts, shown as a SORT stage.
  • Poor compound index order.
  • Unanchored regexes, which scan everything.
  • Large $skip values.
  • $lookup without an index on the foreign field.

Diagnose it

Record slow operations for a short time, and then explain the worst.

bash
// In mongosh
db.setProfilingLevel(1, { slowms: 100 });

// Worst recent operations
db.system.profile.find({}, {op:1,ns:1,millis:1,docsExamined:1,nreturned:1,planSummary:1})
  .sort({ millis: -1 }).limit(5);

// Examine one query
db.orders.find({ customerId: 42, status: "open" }).sort({ createdAt: -1 })
  .explain("executionStats");

db.setProfilingLevel(0);

Fixes

Create compound indexes in Equality, Sort, Range order: for the query above, { customerId: 1, status: 1, createdAt: -1 }. Replace large $skip with range pagination on an indexed field. Anchor regexes with a prefix. Project only the fields you need, as covered queries can avoid reading documents altogether. Drop unused indexes, which you can identify with $indexStats, because each one slows writes.

Why ESR works

An index is sorted by its fields in order. Equality fields first narrow it to one contiguous section. Within that section, a sort field already appears in sorted order, so no sort is needed. A range field placed before the sort would split that order into many pieces and force an in-memory sort. Placing the range last avoids it, at the small price of examining a few extra index keys. Check the results with explain: a good plan shows IXSCAN with no blocking SORT stage and totalDocsExamined close to nReturned.

Catch it automatically

Add database spans through APM, so a slow query appears inside the request it delayed. Use MongoDB monitoring for server-level signals such as cache pressure and connection counts.

Frequently asked questions

Should the profiler stay on?

Level 1 with a sensible threshold is usually acceptable, but it is safest to use it for limited periods.

Why is my index not used?

Field order may not match the query, or the planner found another plan cheaper.

How many indexes are too many?

There is no single number. Each one has a write cost, so remove those with no use.

Check it now, free

Watch your own site and services with VitalRix

Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.