MongoDB Indexes, Explain Plans, and Performance

Create indexes, inspect query plans, and troubleshoot common MongoDB query performance issues.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Create indexes
Create a single-field index
db.users.createIndex({ email: 1 })

# Index one frequently filtered field.

Create a compound index
db.orders.createIndex({ status: 1, created_at: -1 })

# Index fields used together in filters or sorts.

Enforce uniqueness with an index
db.users.createIndex({ email: 1 }, { unique: true })

# Prevent duplicate values at write time.

Create a text index
db.articles.createIndex({ title: "text", body: "text" })

# Enable text search over string content.

List indexes on a collection
db.users.getIndexes()

# Inspect existing indexes.

## Explain and tune
Explain a query
db.orders.find({ status: "paid" }).sort({ created_at: -1 }).explain("executionStats")

# Show the execution plan for a `find()` query.

Force a specific index with hint
db.orders.find({ status: "paid" }).hint({ status: 1, created_at: -1 })

# Test how a query behaves with a chosen index.

Hide an index for testing
db.orders.hideIndex({ status: 1, created_at: -1 })

# Temporarily hide an index from the planner.

Inspect collection stats
db.runCommand({ collStats: "orders" })

# View storage and index metrics for a collection.

Drop an index
db.orders.dropIndex({ status: 1, created_at: -1 })

# Remove an unneeded index.

Recommended next

No recommendations yet.