MongoDB
Beginner
1 min read
Index Strategies and EXPLAIN
Example
// Run explain to see execution plan
const plan = db.orders.find(
{ userId: ObjectId("aaa"), status: "shipped" }
).explain("executionStats")
// Key fields to inspect in the output:
// plan.executionStats.executionTimeMillis — query duration
// plan.executionStats.totalDocsExamined — docs scanned
// plan.executionStats.totalDocsReturned — docs returned
// plan.queryPlanner.winningPlan.stage — IXSCAN or COLLSCAN
// Force a specific index with hint()
db.orders.find({ userId: ObjectId("aaa") })
.hint({ userId: 1, status: 1 })
// Enable the query profiler (log queries slower than 100ms)
db.setProfilingLevel(1, { slowms: 100 })
// View profiler output
db.system.profile.find().sort({ ts: -1 }).limit(10)
// Partial index — only index documents matching a filter
db.orders.createIndex(
{ createdAt: 1 },
{ partialFilterExpression: { status: { $in: ["pending", "processing"] } } }
)