Finding slow MongoDB queries and fixing them with the right index
MongoDB is forgiving. You can ship an app with no indexes beyond _id and it will feel fast for months, because every collection is small. Then one day the orders collection passes a few hundred thousand documents and a screen that used to open instantly takes four seconds.
This is the routine I follow every time.
1. Find the slow queries
Don’t guess which query is slow. Ask the database. The profiler records operations that take longer than a threshold:
// In mongosh, on the app's database.
// Level 1 = log only operations slower than slowms.
db.setProfilingLevel(1, { slowms: 100 })
Use the app normally for a while (or ask the team to), then look at what was caught:
db.system.profile
.find({}, { op: 1, ns: 1, millis: 1, command: 1, planSummary: 1 })
.sort({ millis: -1 })
.limit(10)
The planSummary field is the quick tell. COLLSCAN means MongoDB read the whole collection. IXSCAN { companyId: 1 } means it used an index.
When you are done, turn it off with db.setProfilingLevel(0). The profiler adds a little overhead, so I leave it on only while investigating. Even with it off, MongoDB still writes operations slower than slowms to its log file.
2. Read explain() properly
Take one slow query and run it with explain:
db.orders
.find({ companyId: 42, status: 'paid', createdAt: { $gte: ISODate('2026-10-01') } })
.sort({ createdAt: -1 })
.explain('executionStats')
The output is long. Only a few numbers matter:
| Field | What it tells you |
|---|---|
executionStats.nReturned |
Documents the query returned |
executionStats.totalDocsExamined |
Documents MongoDB had to read |
executionStats.totalKeysExamined |
Index entries it walked |
executionStats.executionTimeMillis |
Time taken on the server |
winningPlan.stage (and its children) |
COLLSCAN, IXSCAN, FETCH, SORT |
The ratio that matters is documents examined to documents returned. If the query returns 40 documents but examined 380,000, it is doing a lot of work for nothing. In a well-indexed query those numbers are close.
Also look for a SORT stage. It means MongoDB sorted the results in memory after finding them, which is slow on large results. Past 100 MB it has to spill to disk (or, on older versions, fails outright).
3. Design the index with Equality, Sort, Range
For a compound index, the order of fields matters a lot. The rule that works almost every time is ESR:
- Equality fields first: the ones you match exactly (
companyId: 42,status: 'paid'). - Sort fields next: what you sort by (
createdAt: -1). - Range fields last:
$gte,$lt,$inwith many values, regex prefixes.
For the query above, createdAt is both the sort and the range, so the index is:
db.orders.createIndex({ companyId: 1, status: 1, createdAt: -1 })
Run the same explain again. You want to see IXSCAN with no SORT stage, and totalDocsExamined close to nReturned.
4. Things that catch people out
- One index can serve several queries. An index on
{ companyId: 1, status: 1, createdAt: -1 }also serves queries oncompanyIdalone, and oncompanyId+status. It does not help a query onstatusalone. Before adding a new index, check whether an existing one already covers the query’s leading fields. - Every index costs writes. Each insert and update has to update every index on the collection. Ten indexes on a busy collection will slow down writes and use RAM. Remove indexes nobody uses:
db.orders.aggregate([{ $indexStats: {} }])shows how often each one has been used since the last restart. - Case-insensitive search. A regex like
/^ram/icannot use a normal index efficiently. Store a lowercased copy of the field and query that, or use a collation index, or a text or Atlas Search index for real search. - Build indexes deliberately in production. With Mongoose,
autoIndexcreates indexes when the app starts, which is handy in development and risky on a large production collection. I turn it off in production and create indexes as a planned step.
// app.module.ts (NestJS + Mongoose)
MongooseModule.forRoot(process.env.MONGO_URL, {
autoIndex: process.env.NODE_ENV !== 'production',
});
5. Check the fix where it matters
An index that makes the query fast in mongosh should make the screen fast too. Reload the page with the browser’s Network tab open and confirm the API call actually got faster. If it did not, the time is going somewhere else: an N+1 loop in the code, a huge response, or a slow external API. That is a different fix, and I cover the usual suspects in why your business app feels slow.
Summary
- Turn on the profiler, catch the slow queries, then turn it off
- Use
explain('executionStats')and compare documents examined to documents returned - Order compound index fields as Equality, Sort, Range
- Remove indexes you don’t use and build big ones deliberately
- Confirm the improvement in the real app, not only in the shell