Stop 06 · MongoDB Data Modeling & AggregationTopics · 7/8

Explain Plans and Query Performance

Part of the MERN Stack Roadmap

In short

"The API is slow" is a feeling. explain() turns it into facts: did the query use an index, and how many documents did MongoDB read to return ten? It's the first tool to reach for on a slow endpoint.

explain() shows whether a query used an index (IXSCAN) or scanned the whole collection (COLLSCAN), and how many documents it examined. It is the first tool for fixing slow queries.

The jaadu leans into an auto rickshaw, studying a big paper map with the driver as they trace a route along a flyover.

Think of it like this

Asking the auto driver for his route

Before you agree on a fare, you ask the auto driver which way he'll go. Main road via the flyover (IXSCAN) or through every lane in the old city (COLLSCAN)? explain() makes the database tell you its route before you complain about the trip.

Watch it happen

Same query, before and after an index

COLLSCAN

  • stage: COLLSCAN
  • totalDocsExamined: 200000
  • nReturned: 20
  • Reads every document to find 20

IXSCAN

  • stage: IXSCAN then FETCH
  • totalKeysExamined: 20
  • totalDocsExamined: 20
  • Jumps straight to the matching entries

Aim for docs examined close to documents returned. A big gap means a missing or wrong index.

The big ideas

What you need to know

executionStats mode

explain("executionStats") actually runs the query and reports what it did, not just the plan.

Three numbers

nReturned, totalKeysExamined and totalDocsExamined. Compare examined with returned.

Watch for SORT

A SORT stage means sorting in memory. An index that matches the sort removes it.

Find slow queries

Atlas Query Profiler and Performance Advisor list slow queries and suggest indexes.

How it works

Fixing a slow endpoint

  1. 1

    Find the query

    Log or copy the exact filter, sort and limit the endpoint runs.

  2. 2

    Run explain

    Use .explain("executionStats") in mongosh or Compass's Explain tab.

  3. 3

    Read the stages

    Look for COLLSCAN, in-memory SORT and a big examined-to-returned ratio.

  4. 4

    Add or fix an index

    Create a compound index following Equality, Sort, Range.

  5. 5

    Explain again

    Confirm IXSCAN and lower examined counts.

See it in code

Walk through the code

js
1const q = { category: "kitchen", price: { $lt: 500 } };2 3db.products.find(q).sort({ createdAt: -1 }).limit(20).explain("executionStats");4// winningPlan: SORT <- COLLSCAN5// executionStats: { nReturned: 20, totalKeysExamined: 0, totalDocsExamined: 200000 }6 7db.products.createIndex({ category: 1, createdAt: -1, price: 1 });8 9db.products.find(q).sort({ createdAt: -1 }).limit(20).explain("executionStats");10// winningPlan: LIMIT <- FETCH <- IXSCAN { category: 1, createdAt: -1, price: 1 }11// executionStats: { nReturned: 20, totalKeysExamined: 26, totalDocsExamined: 20 }

1/3Without a suitable index: a full collection scan plus an in-memory sort.

Before and after. The output is trimmed here. In mongosh, look under queryPlanner.winningPlan and executionStats.

Save yourself the pain

Common mistakes

Oops

Adding an index for every field "just in case".

Do this instead

Use explain on real queries and add indexes that match them. Extra indexes slow every write.

Oops

Testing performance on a collection with 50 documents.

Do this instead

Everything is fast with tiny data. Insert realistic volumes before judging a query.

Your mission

Speed up a query

~30 min

Quick check

explain shows nReturned: 10 and totalDocsExamined: 150000. What does that tell you?

Go deeper

  1. 1Run explain('executionStats') on a slow query and note totalDocsExamined.
  2. 2Add the right index and compare the numbers again.
  3. 3Check the Atlas Performance Advisor for index suggestions on real traffic.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge