How would you approach diagnosing and fixing slow queries in MongoDB?

Instruction: Discuss the steps you would take to identify and optimize slow queries in a MongoDB database.

Context: This question assesses the candidate's ability to troubleshoot and optimize query performance, a critical skill for maintaining efficient database operations.

Updated

Official answer

Capture the slow query shape, parameters, data distribution, frequency and user-visible impact. Use appropriately configured slow-query logs or profiling, accounting for overhead and sensitive query data. Separate server execution time from network, connection-pool and application delays.

Inspect explain with executionStats on representative inputs. Compare returned rows, documents/keys examined, sort behavior, index bounds and shard targeting. A high examined-to-returned ratio can suggest unnecessary work, but zero-result queries and workload selectivity need context.

Consider a compound index matching filters/sort, a bounded query, or a model change only after identifying the cause. Check collation, regex shape, large skip values, join fan-out and stale assumptions. An extra index also costs storage and write work; preserve required uniqueness when removing one.

Compare identical workloads before and after: result equality, p50/p95/p99 latency, throughput, errors and resource use. Separate cold-cache and warm-cache measurements. DAU measures engagement and cannot by itself prove that a query became faster.

Roll out with monitoring and a reversal plan. Retest skewed inputs and concurrent load, and keep the diagnostic evidence so a future regression can be distinguished from changed traffic or data size.

MongoDB explain results, profiler

Related Questions