MongoDB Indexes: Types and Usage
MongoDB Indexes: Types & Usage
Without indexes, MongoDB must perform a Collection Scan (COLLSCAN), reading every document on disk to satisfy a query. Indexes maintain an ordered B-Tree data structure to enable logarithmic time lookups.
Index Types Comparison
| Index Type | Creation Syntax | Primary Use Case | Key Constraint / Note |
|---|---|---|---|
| Single Field | createIndex({ email: 1 }) |
Exact match or range queries on a single attribute | Default unique index on _id |
| Compound | createIndex({ dept: 1, salary: -1 }) |
Multi-field queries, filtering, and sorting | Prefix rule applies: index on (A, B) covers queries on (A) and (A, B), but not (B) alone |
| Multikey | createIndex({ tags: 1 }) |
Indexing elements within array fields | Automatically creates index entries for each array element |
| Partial | createIndex({ age: 1 }, { partialFilterExpression: { age: { $gte: 21 } } }) |
Index only documents meeting specific criteria | Saves disk space and memory overhead |
| TTL Index | createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }) |
Automatic document expiration and cleanup | Requires a Date field; background cleanup runs every 60 seconds |
| Text Index | createIndex({ title: "text", body: "text" }) |
Full-text search with tokenization and stemming | Only one text index allowed per collection |
Interview Best Practices
- Use
explain("executionStats")to verify queries use IXSCAN instead of COLLSCAN. - Follow the ESR Rule (Equality, Sort, Range) when structuring compound index fields.