Modeling and indexes
Index from real queries
Create compound indexes from filters and sorts, then read executionStats instead of assuming an index improved the workload.
9 minute lesson
Without a useful index, MongoDB may scan the collection. Indexes speed supported reads but add storage and write work.
Use explain('executionStats') on a representative query. Compare returned documents, examined documents, examined keys, and the execution stages. Compound field order must match the important equality, range, and sort patterns.
Load enough sample documents to make a scan visible. Add one justified index and compare the plan before and after.
Measure the query before and after one index:
db.animals.find({ species: 'cat' }).sort({ age: -1 }).explain('executionStats')
db.animals.createIndex({ species: 1, age: -1 })
db.animals.find({ species: 'cat' }).sort({ age: -1 }).explain('executionStats')
Compare execution stages, totalDocsExamined, totalKeysExamined, and nReturned. Keep the index only when it supports an important query and its write cost is acceptable.
Lesson completed