The document discusses query planning in MongoDB. It covers the three stages of query planning: index selection, access plan generation, and analysis. An example .find() query is broken down to demonstrate how the _id index is selected and used to perform an index scan between bounds of 7 and infinity. The stages that queries can produce or consume data are also explained. Finally, plan ranking is briefly covered, where plans are run and the most efficient one is selected based on results produced per work unit executed.
12. Query planning has three stages.
Index
Selection
Access
Plan Generation
Analysis
Sort, Project, etc.
13. Index Selection Access Analysis
There are three index “types”;
predicates are matched to indexes.
Geo
Text
B-Tree
14. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
predicate
Which indexes
are useful?
Index Selection Access Analysis
15. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
predicate
_id index is the
relevant index.
Index Selection Access Analysis
16. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
Index Selection Access Analysis
predicate
Perform index scan on { _id: 1 } index
with bounds 7 < _id <= infinity.
17. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
predicate
Perform index scan on { _id: 1 } index
with bounds 7 < _id <= infinity.
The predicate is fully covered by the index!
Index Selection Access Analysis
18. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
predicate
What if multiple
indexes could work?
Index Selection Access Analysis
19. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
Index Selection Access Analysis
projection sort
What other processing is needed?
20. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
projection
What other processing is needed?
Index scan on {_id: 1} =>
Results are already sorted by {_id: 1}!
Index Selection Access Analysis
21. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
What other processing is needed?
Index on {_id: 1} & only need _id field =>
No need to fetch documents from disk!
Index Selection Access Analysis
22. .find({ _id: { $gt: 7 }}, { _id: 1 }).sort({ _id: 1 });
The actual query solution tree:
RESULTS
Index Selection Access Analysis
IXSCAN
PROJ