Advanced query optimization techniques in MongoDB.
Instruction: Describe advanced techniques for optimizing MongoDB queries, focusing on scenarios with large datasets and complex aggregations.
Updated
Official answer
Optimize from the query's semantics and measured plan. Compare examined keys/documents, returned rows, sort work, shard targeting and tail latency on realistic inputs. An index scan is not always cheaper than a collection scan for a very unselective query.
Design compound indexes around supported filter/sort patterns. Partial indexes help only when the query implies the partial condition; hashed indexes do not accelerate arbitrary range queries. Measure index write/storage costs and preserve required constraints.
In pipelines, move selective filters earlier only when equivalent. MongoDB already performs eligible projection/filter optimizations, so an early project is not a universal speed trick. Bound lookup/unwind fan-out and aggregate at the correct grain.
Facet processes several sub-pipelines over the same input, but does not promise a speedup. It cannot spill to disk, has a 100 MB limit during its processing, and the final BSON document still has a 16 MiB limit. allowDiskUse does not remove those restrictions. Avoid collecting unbounded result arrays into one facet output.
For repeated expensive results, consider a materialized summary or cache with explicit freshness, invalidation and tenant-aware keys. Verify output equality and behavior under skew, concurrency and cache misses before deploying an optimization.