Run Explain on a pipeline
Use a development MongoDB instance and an empty scratch database. Run this setup in mongosh with permission to write to the scratch database. Use a fresh database if you repeat the exercise.
const scratch = db.getSiblingDB(
"keplergrid_explain"
)
const orders = Array.from(
{ length: 4000 },
(_, i) => {
const id = String(i % 1000)
.padStart(4, "0")
return {
customerId:
"customer-" + id,
status: i % 2
? "pending"
: "paid"
}
}
)
scratch.orders.insertMany(
orders
)
In KeplerGrid, connect to that MongoDB instance in Read only mode. Open keplergrid_explain.orders, select Aggregation → JSON, paste this pipeline, and click Explain. Explain uses MongoDB execution statistics and requires a MongoDB connection.
[
{ "$match": {
"customerId":
"customer-0042"
} },
{ "$project": {
"_id": 0,
"status": 1
} }
]
COLLSCAN examined 4,000 synthetic orders to return four.Compare the plan after adding an index
Back in mongosh, add an index to the scratch collection. Then run Explain again for the same pipeline in KeplerGrid.
scratch.orders.createIndex(
{ customerId: 1 }
)
customerId_1, the same pipeline examined four keys and four documents and returned the same four orders.| Metric | Before index | After index |
|---|---|---|
| Scan and fetch | COLLSCAN | IXSCAN, FETCH |
| Documents examined | 4,000 | 4 |
| Keys examined | 0 | 4 |
| Returned | 4 | 4 |
Read the plan and counters
COLLSCAN reads documents from the collection. IXSCAN reads index keys. FETCH retrieves matching documents, which this pipeline needs to read status because the index contains customerId.
Compare the counters across runs with the same pipeline and data. Examine the winning plan and index name as well. The selected plan depends on the server, query, indexes and data distribution. The sample counters show the change in work for this run. Execution time can vary even with the same plan.
Check the scope note above the counters. MongoDB sometimes reports statistics for the collection cursor and lists later stages separately. In that case, Returned describes the cursor's output. Expand Raw MongoDB explain (Extended JSON) to inspect the server response.
Debug a pipeline stage by stage or export the full result to CSV or JSON.
Connect to a MongoDB replica set over SSH if your server is behind a bastion.