LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2717 min read

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.

StageMeaning
COLLSCANA full collection scan — every document was examined. Usually a sign a needed index is missing.
IXSCANAn index scan — MongoDB used an index to find matching documents directly.
FETCHRetrieving the full document after locating it via an index.
SORTAn in-memory sort, which can be avoided if an index already provides the needed order.
A COLLSCAN on a Large Collection Is a Red Flag

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

FieldMeaning
totalDocsExaminedHow many documents MongoDB had to look at
nReturnedHow many documents actually matched and were returned
executionTimeMillisHow 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

Only checking explain() during development on a tiny dataset

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.

Ignoring a SORT stage in the output

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.

Next Lesson →

Performance Best Practices