How do you optimize MongoDB query performance?

Answer

Systematic MongoDB query optimization involves profiling, indexing, and schema design: (1) Identify slow queries: enable profiler (db.setProfilingLevel(1, { slowms: 100 })); use Atlas Performance Advisor; check system.profile; look at COLLSCAN stages. (2) Add appropriate indexes: use explain("executionStats") to verify IXSCAN vs COLLSCAN; follow ESR rule for compound indexes (Equality → Sort → Range); consider covered queries (all needed fields in the index); use partial indexes for selective queries; use sparse indexes for optional fields with unique constraints. (3) Aggregation optimization: put $match and $limit as early as possible; use $project early to reduce document size; avoid $unwind + $group when $group suffices; use allowDiskUse for large aggregations; monitor with explain(). (4) Schema optimization: embed data that's always accessed together; avoid fetching large documents for small field subsets; use projections to retrieve only needed fields; avoid large arrays (multikey index overhead); store frequently accessed computed values (denormalize). (5) Connection optimization: use a single MongoClient with connection pooling; don't create new connections per request; set appropriate maxPoolSize. (6) Write optimization: use bulk write operations (bulkWrite, insertMany); use appropriate write concern (don't use w:"majority" for non-critical writes); batch operations when possible. (7) WiredTiger cache: ensure working set fits in cache (monitor evictions); properly size cache (50% of RAM). (8) Hardware: SSDs dramatically improve random I/O; adequate RAM for working set.