Indexes and explain
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
create indexes and read query plans.
Planned topics
- Without an index MongoDB does a collection scan (
COLLSCAN). With one it does an index scan (IXSCAN). - Compound index order follows equality, sort, range (ESR rule):
{ productId: 1, createdAt: -1 }. - Check plans with
explain("executionStats"): comparetotalDocsExaminedwithnReturned. - Each index costs write time and memory; build only those queries need. TTL and unique indexes also exist.
Draft outline details
Demonstration
db.reviews.createIndex({ productId: 1, createdAt: -1 })
db.reviews.find({ productId: 42 }).sort({ createdAt: -1 }).explain("executionStats")Look for IXSCAN and totalDocsExamined close to nReturned.
Check your understanding
What does COLLSCAN in a plan tell you?
Show answer
No usable index; every document was read.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.