SyntaxStudy
Sign Up
MongoDB Index Strategies and EXPLAIN
MongoDB Beginner 1 min read

Index Strategies and EXPLAIN

The explain() method is the primary tool for understanding how MongoDB executes a query. The executionStats verbosity level shows the winning query plan, the number of documents examined versus returned, and execution time. A good index results in an IXSCAN stage (index scan) rather than COLLSCAN (collection scan). The keysExamined to docsReturned ratio should ideally be close to 1:1. Covered queries — where all requested fields are in the index — avoid fetching the actual document entirely and are the most efficient type. The MongoDB Query Analyser in Atlas and the profiler (db.setProfilingLevel) help identify slow queries in production and determine which indexes to add.
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"] } } }
)