All academies
Roadmap
LEVEL 10 · PERFORMANCE

Finding & Fixing Slow Queries

14 min read

Performance work follows a loop: measure → diagnose → fix → verify. The main tools are explain(), the database profiler, and Atlas's Performance Advisor. Practice with the performance analyzer.

The three explain numbers

totalKeysExamined (index entries read), totalDocsExamined (documents read), nReturned (results). Healthy queries have all three close together. docsExamined >> nReturned → missing/weak index. keysExamined >> nReturned → index isn't selective enough.

Common fixes

1. Add an index matching the query (remember ESR).

2. Use projections to return only needed fields.

3. Replace skip() pagination with range-based pagination (_id > lastSeen).

4. Avoid $where and unanchored regex.

5. Batch writes with insertMany/bulkWrite.

6. Watch for in-memory sorts — explain shows a SORT stage when no index supports the sort.

mongosh
// slow: in-memory sort
db.orders.find({ userId: 7 }).sort({ date: -1 })
// fix:
db.orders.createIndex({ userId: 1, date: -1 })

The profiler

db.setProfilingLevel(1, { slowms: 100 }) logs every operation slower than 100 ms into system.profile — your slow-query log inside the database.

Try it yourself

db.orders.find({ userId: 101 }).explain()
Run in Shell

Check your understanding

Q1.

explain() shows stage SORT with no supporting index. What does this mean?

code
db.orders.find({ userId: 7 }).sort({ date: -1 }).explain()
Q2.

Why does skip(100000) get slow?

Q3.

db.setProfilingLevel(1, { slowms: 100 }) logs operations slower than 100ms.