MongoDB Indexing Cheat Sheet

1. Why Indexes Matter

2. Creating Indexes

Basic Syntax

db.collection.createIndex({ field: 1 })        // ascending
db.collection.createIndex({ field: -1 })       // descending
db.collection.createIndex({ a: 1, b: -1 })     // compound

Useful Options

db.collection.createIndex({ email: 1 }, { unique: true })
db.collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }) // TTL
db.collection.createIndex({
  status: 1
}, {
  partialFilterExpression: { status: { $exists: true } }
})

3. Index Types

Single‑Field Index

Compound Index

Multikey Index

Text Index

db.posts.createIndex({ title: "text", body: "text" })

Hashed Index

db.users.createIndex({ userId: "hashed" })

TTL Index

4. Query Patterns Indexes Support

Equality

db.users.find({ email: "[email protected]" })

Range

db.orders.find({ total: { $gt: 100 } })

Sort

db.logs.find().sort({ timestamp: -1 })

Combined Filter + Sort

Index must match both filter and sort order. Example:

{ status: 1, createdAt: -1 }

5. How to Read explain()

db.collection.find({ a: 5 }).explain("executionStats")

Key Metrics

6. Best Practices

7. Common Pitfalls

8. Quick Reference Table

Feature Index Type Notes
Equality queries Single / Compound Fastest lookup
Range queries Single / Compound Range fields must be last
Array fields Multikey One index entry per element
Full‑text search Text One per collection
Sharding key Hashed Uniform distribution
Auto‑expiration TTL Deletes documents automatically