What is the explain() method in MongoDB?

Answer

The explain() method returns information about how MongoDB executes a query — the query execution plan. Essential for query optimization. Usage: db.users.find({ email: "alice@example.com" }).explain("executionStats"). Verbosity levels: "queryPlanner" (default): shows the winning plan without executing; "executionStats": executes the query, shows execution statistics; "allPlansExecution": executes all candidate plans, shows statistics for each. Key fields in the output: winningPlan.stage: the primary operation — IXSCAN (index scan — good!), COLLSCAN (collection scan — slow for large collections!), SORT (in-memory sort — may be slow), FETCH (retrieve documents from disk); executionStats.nReturned: number of documents returned; executionStats.totalKeysExamined: index keys examined; executionStats.totalDocsExamined: documents examined; executionStats.executionTimeMillis: total execution time. Efficiency ratio: good query: nReturned ≈ totalKeysExamined ≈ totalDocsExamined (minimal scanning). Bad: totalDocsExamined >> nReturned (scanning many docs to find few). Covered query: when all fields needed are in the index — no document fetch needed. IXSCAN only, totalDocsExamined = 0. Forcing an index: .hint({ email: 1 }) — force use of a specific index for testing. Use explain() with every new query in production to verify index usage.