explain() & Query Performance
Inspect exactly how MongoDB executes a query using explain(), and distinguish an index scan from a full collection scan.
Why explain() Matters
Rather than guessing whether a query uses an index, explain() shows MongoDB's actual execution plan — exactly how many documents it examined, whether it used an index, and how long each stage took.
Running explain()
db.users.find({ email: "ada@example.com" }).explain("executionStats");COLLSCAN vs IXSCAN
The explain() output's winningPlan.stage field reveals which strategy MongoDB used.
| Stage | Meaning |
|---|---|
| COLLSCAN | A full collection scan — every document was examined. Usually a sign a needed index is missing. |
| IXSCAN | An index scan — MongoDB used an index to find matching documents directly. |
| FETCH | Retrieving the full document after locating it via an index. |
| SORT | An in-memory sort, which can be avoided if an index already provides the needed order. |
Seeing COLLSCAN in a query's explain() output for a frequently-run query on a large collection is a strong signal that an index is missing for that query pattern.
Key Fields in the Output
| Field | Meaning |
|---|---|
| totalDocsExamined | How many documents MongoDB had to look at |
| nReturned | How many documents actually matched and were returned |
| executionTimeMillis | How long the query took to execute |
A well-indexed query has totalDocsExamined close to nReturned — examining far more documents than were actually returned is a sign of an inefficient or missing index.
Common Beginner Mistakes
A missing index is often invisible on a small collection but becomes a serious problem at production scale — test explain() against realistic data volumes when possible.
An in-memory sort on a large result set can be slow and memory-intensive — often addressable by including the sorted field in a compound index.
FAQs
Not every one — focus on queries that run frequently or on large collections, where an inefficient plan has the most real-world impact.
Yes — Atlas's Performance Advisor and Query Profiler visualize this same information, along with automatic index recommendations.
Summary
explain() reveals exactly how a query executes, making COLLSCAN vs IXSCAN and examined-vs-returned document counts visible and actionable. Next, you'll wrap up indexing with a broader set of performance best practices.