Explain plan analysis (queryPlanner, executionStats) in MongoDB - Time & Space Complexity
When we run a query in MongoDB, it does many steps to find the data.
We want to know how the work grows as the data gets bigger.
Analyze the time complexity of the explain plan for a find query.
db.collection.find({ age: { $gt: 25 } }).explain("executionStats")
This command shows how MongoDB plans and runs the query to find documents where age is greater than 25.
Look at the main repeated work MongoDB does to answer the query.
- Primary operation: Scanning documents or index entries to check the age condition.
- How many times: Once for each document or index entry it examines.
As the number of documents grows, MongoDB checks more entries.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the number of documents checked.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of documents MongoDB must examine.
[X] Wrong: "Explain plans always show constant time queries."
[OK] Correct: Explain plans show how much work depends on data size; many queries scan many documents, so time grows with data.
Understanding explain plans helps you see how queries work behind the scenes and how their cost changes with data size.
"What if we add an index on the age field? How would the time complexity shown in the explain plan change?"