MongoDB & NoSQL (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What are Compound Indexes and Index Prefixes in MongoDB?
senior LevelMost AskedSystem DesignDatabases & SQL
In Simple Words:
A compound index indexes multiple fields (e.g. { status: 1, createdAt: -1 }):
- Index Prefixes: Subsets of the index starting from the leftmost field:
{ status: 1 }is an index prefix (can be used by queries filtering onstatus).{ createdAt: -1 }is NOT a prefix and cannot be used alone!
- ESR Rule (Equality, Sort, Range): Best practice for compound index field ordering:
- Equality fields first.
- Sort fields second.
- Range filter fields (
$gt,$lt) last.