MongoDB中explain('executionStats')与普通explain()的区别及选用疑问
explain() vs explain('executionStats'): What's the Difference? Great question! Let’s clear up the confusion between these two explain variants and when to use each one.
Core Differences
First, let’s break down what each call actually does:
Default
explain()(no arguments)
In MongoDB 3.0+, this uses thequeryPlannermode. It only returns details about how MongoDB selects the optimal query plan—like which index it picked, what other candidate indexes were considered, and the structure of the chosen plan. Crucially, it does not run the query or return actual execution statistics (like how many documents were scanned, how long the query took, or how many results were returned).explain('executionStats')
This uses theexecutionStatsmode. It not only returns the query plan details but also executes the query (for read operations likefind()) and returns granular performance metrics. You’ll get fields like:executionTimeMillis: Total time taken to run the querytotalDocsExamined: Number of documents scanned (a key metric for spotting inefficient queries)totalKeysExamined: Number of index entries scannednReturned: Number of documents returned by the query
Why Did You See Identical Results?
If you’re seeing the same output from both calls, there are a few possible reasons:
- Older MongoDB Version: Before MongoDB 3.0,
explain()defaulted to returning execution stats similar toexecutionStats. If you’re on an older version, this could explain the overlap. - Overlooking Nested Fields: The
executionStatsmode adds a top-levelexecutionStatsobject with all the performance metrics. Double-check your output—you might have missed this nested section in the defaultexplain()result.
When to Choose Which?
- Use default
explain()if you only need to verify which index MongoDB is using, or check if there are better index candidates. It’s lightweight because it doesn’t execute the query, making it ideal for quick plan validation. - Use
explain('executionStats')when you need to debug query performance. This is essential for identifying slow queries, checking if your indexes are actually reducing document scans, or confirming that your query is running efficiently.
A Note on Your Code
Quick side note: In your code, you’re running the same query twice—once via explain('executionStats') (which executes the query) and once via toArray(). If you don’t need to run the query twice, you could refactor to get the explain stats without re-executing, but that’s a minor optimization.
内容的提问来源于stack exchange,提问作者yodalr

