Without indexes, MongoDB must inspect every single document in a collection to satisfy a query—an expensive operation known as a Collection Scan (COLLSCAN). Proper Indexing Strategies turn sluggish multi-second queries into sub-millisecond Index Scans (IXSCAN).
1. Types of MongoDB Indexes
1
Single Field Index: Index on a single attribute (db.users.createIndex({ email: 1 })).
2
Compound Index: Index on multiple fields (db.courses.createIndex({ category: 1, price: -1 })).
3
Unique Index: Guarantees no two documents share the same value ({ unique: true }).
4
TTL (Time-To-Live) Index: Automatically deletes documents after a designated lifespan!
5
Text Index: Powers full-text keyword searches across text fields.
2. The ESR Rule for Compound Indexes
When designing compound indexes for complex queries containing Equality, Sorting, and Range conditions, follow the ESR (Equality, Sort, Range) Rule:
1
E - Equality: Fields queried with exact matches (status: 'ACTIVE') go first.
2
S - Sort: Fields used for ordering (sort: { createdAt: -1 }) go second.
3
R - Range: Fields queried with range operators (price: { $gte: 100 }) go last.