Intermediate LevelMongoDB & Mongoose
Compare MongoDB Index Intersection versus Compound Indexing performance.
❓ Interview Prompt: Compare Index Intersection (combining two single-field indexes at runtime) vs Compound Indexes (pre-sorted multi-field trees).
When a query filters on multiple fields, MongoDB can choose between two execution approaches:
1
Index Intersection: Merges results from two separate single-field indexes at runtime.
2
Compound Index: Uses a single multi-field index ('{ age: 1, status: 1 }').
Winner: Compound indexes ALWAYS outperform index intersection because compound indexes maintain pre-sorted multi-field key ordering in memory!
Code Implementation Example
typescript
import { UserModel } from './models/User';
// Compound Index (Fastest! Outperforms single-field index intersection)
UserModel.schema.index({ age: 1, status: 1 });💡Creating compound index outperforming single-field index intersection.
🎯 Interview Key Takeaway
Prefer compound indexes over relying on runtime index intersection for multi-field queries.
#Index Intersection#Compound Index#Performance#Intermediate
Back to all MongoDB & Mongoose Questions→