Query Plans with explain()
When a query is slow, the first question is: how did MongoDB run it? Did it use an index, or read the whole collection? explain() answers that by returning the query plan instead of the results.
db.collection.find(filter).explain() // the chosen plan
db.collection.find(filter).explain('executionStats') // plan + numbers from actually running it
db.collection.aggregate(pipeline, { explain: true }) // for pipelinesThe full explain output is long and contains things that change from run to run (timings, host names, cache flags). In practice you look at a handful of fields, and that is what the examples here print.
Plan stages
A plan is a tree of stages. The ones you'll meet most:
| Stage | Meaning |
|---|---|
COLLSCAN |
collection scan: every document is read |
IXSCAN |
index scan: walks a range of index keys |
FETCH |
loads the documents the index keys point to |
SORT |
an in-memory sort (no index provided the order) |
PROJECTION_* |
applies a projection |
LIMIT / SKIP |
applies limit / skip |
EXPRESS_IXSCAN / IDHACK |
the fast path for an exact _id (or unique index) lookup |
This helper walks the tree and lists the stage names from top to bottom:
function planStages(explainResult) {
const out = [];
let node = explainResult.queryPlanner.winningPlan;
node = node.queryPlan ?? node; // newer engines wrap the plan
while (node) {
out.push(node.stage + (node.indexName ? '(' + node.indexName + ')' : ''));
node = node.inputStage;
}
return out.join(' <- ');
}
print(planStages(db.orders.find({ status: 'shipped' }).explain()));
db.orders.createIndex({ status: 1 });
print(planStages(db.orders.find({ status: 'shipped' }).explain()));COLLSCAN
FETCH <- IXSCAN(status_1)
Without an index: a COLLSCAN. With one: an IXSCAN on status_1 feeding a FETCH.
executionStats: counting the work
'executionStats' mode runs the query and reports what it cost. The three numbers to compare are:
nReturned: documents returned,totalKeysExamined: index entries read,totalDocsExamined: documents read.
In an ideal query all three are about equal. If totalDocsExamined is much bigger than nReturned, the server is reading documents only to throw them away: a sign of a missing or poorly chosen index.
function cost(cursor) {
const s = cursor.explain('executionStats').executionStats;
return `returned ${s.nReturned}, keys ${s.totalKeysExamined}, docs ${s.totalDocsExamined}`;
}
const query = { category: 'equipment', price: { $lt: 40 } };
print('no index: ', cost(db.products.find(query)));
db.products.createIndex({ category: 1 });
print('category index: ', cost(db.products.find(query)));
db.products.createIndex({ category: 1, price: 1 });
print('compound index: ', cost(db.products.find(query).hint({ category: 1, price: 1 })));no index: returned 4, keys 0, docs 20
category index: returned 4, keys 6, docs 6
compound index: returned 4, keys 4, docs 4
The single-field index narrowed the search to the 6 equipment products; the compound index found exactly the 4 matches. (hint() forces a specific index, which is useful for comparisons like this.)
Covered queries
If the filter and the projection use only fields in the index (and _id is excluded), MongoDB can answer from the index alone, without a FETCH. Such a query is covered:
function planStages(e) {
const out = [];
let node = e.queryPlanner.winningPlan;
node = node.queryPlan ?? node;
while (node) { out.push(node.stage); node = node.inputStage; }
return out.join(' <- ');
}
db.products.createIndex({ category: 1, price: 1 });
const covered = db.products.find({ category: 'tea' }, { _id: 0, category: 1, price: 1 }).explain('executionStats');
print(planStages(covered), '| docs examined:', covered.executionStats.totalDocsExamined);PROJECTION_COVERED <- IXSCAN | docs examined: 0
Zero documents examined: the answer came straight from the index.
Sorts without an index
A SORT stage means MongoDB had to sort the results in memory. With an index that matches the sort order, the stage disappears:
function hasSortStage(e) {
let node = e.queryPlanner.winningPlan;
node = node.queryPlan ?? node;
while (node) { if (node.stage === 'SORT') return true; node = node.inputStage; }
return false;
}
print(hasSortStage(db.customers.find().sort({ joined: -1 }).explain()));
db.customers.createIndex({ joined: -1 });
print(hasSortStage(db.customers.find().sort({ joined: -1 }).explain()));true
false
Tip: In MongoDB Compass and Atlas the Explain Plan tab draws the same tree visually, and Atlas's Performance Advisor suggests indexes based on your slow queries.
Test yourself
Which plan stage means that every document in the collection was read?
- IXSCAN
- FETCH
- COLLSCAN
- SORT
A query returns 10 documents but totalDocsExamined is 50,000. What does that suggest?
- The query is optimal
- A suitable index is missing
- The collection is corrupted
- The projection is wrong
When is a query 'covered'?
- When it uses $text
- When all filtered and returned fields are in the index, so no documents are fetched
- When it returns no documents
- When it has a hint()