intermediate
Indexes
Create compound, multikey, text, partial, and TTL indexes for query shapes while watching write amplification.
Indexes in MongoDB are B-tree structures (with specialized variants) that match query predicates, sort order, and covered projections. Design them from `explain("executionStats")`, not from every field in the schema.
// Compound index follows equality → sort → range rule
db.orders.createIndex({ customerId: 1, createdAt: -1, status: 1 })
db.orders.find({ customerId: "c_12", status: "open" })
.sort({ createdAt: -1 })
.limit(20)
| Index type | Typical use | |------------|-------------| | Single / compound | Equality, sort, range on known paths | | Multikey | Indexing array elements | | Text | Tokenized search on string fields | | Partial | Smaller index when predicate is selective | | TTL | Auto-expire documents by date field |
Every index adds write amplification and RAM pressure. The `_id` index always exists. A query that cannot use an index efficiently may COLLSCAN — acceptable only at small scale.
On interviews: walk through one real query, the index that serves it, and what happens to writes.
Common pitfalls: indexing low-cardinality fields alone; compound index field order mismatch; multikey indexes on fast-growing arrays; too many indexes slowing ingestion; assuming OR conditions use one index well.
The trade-off is read speed versus write and memory cost — each extra index is a promise to maintain ordering on every insert, update, and delete touching indexed paths.
Checklist:
- Show predicate, sort, and projection for a hot query.
- Pick compound field order deliberately.
- Use partial or TTL indexes when policy allows.
- Read executionStats for COLLSCAN and examined docs.