A senior developer scans explain('executionStats') for a systematic list of red flags: high totalDocsExamined vs. nReturned, full collection scans (COLLSCAN), inefficient index use, and in sharded clusters, unintentional scatter-gather operations.
When you append .explain("executionStats") to your query, MongoDB doesn't just plan the query; it actually executes the winning plan selected by the query optimizer and returns detailed statistics about that execution . This means the output reflects real resource consumption, not just a theoretical plan. Understanding this output is key to moving beyond guessing and into data-driven query optimization .
A senior developer scans this output not just for correctness, but for efficiency and scalability. The presence of an index doesn't mean it's the right index, and a low execution time on a small dataset can hide massive problems waiting to appear at scale. Let's walk through the key sections and the specific red flags we look for.
The first section a senior dev looks at is executionStats. It provides the high-level metrics that immediately signal the query's health .
The ideal state, indicating a highly efficient, well-indexed query, is nReturned == totalKeysExamined == totalDocsExamined . This means the query used the index to pinpoint exactly the right documents and fetched only those.
A senior dev's alarm bells ring with the following patterns:
After the high-level stats, a senior dev drills into the executionStages tree. This shows the step-by-step process of how the query was executed. The stage name is the most critical piece of information here .
On a sharded cluster, .explain() output becomes even more critical. A senior dev will pay close attention to the shards array, which contains the executionStats for each involved shard .
Ultimately, walking through an .explain() is about answering a core set of questions. If the answer to any of these is 'no' or 'unsure', further investigation is needed.