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
// 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.
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
- Is MongoDB Atlas down? Live status: checked every few minutes, with outage history.
- Response time checker: Measure TTFB with DNS, connect, TLS and server time.
Related reading
- Goroutine leaks in Go: how to find and fix them: Find and fix goroutine leaks in Go: read pprof goroutine profiles, spot blocked channels and missing context cancellation, and use goleak in your tests.
- Redis latency spikes: how to diagnose and fix them: Diagnose Redis latency spikes: find slow commands with SLOWLOG, big keys, fork pauses from persistence, swapping and network delay, using built-in tools.
- Mixed content errors: how to find and fix them: Fix mixed content warnings on HTTPS pages: find http:// images, scripts and API calls, update CMS URLs and add a Content-Security-Policy upgrade directive.
- 404 Not Found: how to find and fix broken pages: Find and fix 404 errors: broken internal links, moved pages, case-sensitive paths and soft 404s, with commands and advice on what actually affects SEO.
- 500 Internal Server Error: how to find the cause: A 500 error means your code failed. Find the exception behind it fast with logs, traces and error tracking, and learn how to prevent repeats.
- PostgreSQL idle in transaction: find and fix it: Find and fix PostgreSQL idle in transaction sessions: why they block vacuum and hold locks, which application patterns cause them and which timeout to set.
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.