Database Speed at Scale
MongoDB is flexible, but that flexibility can lead to performance bottlenecks if you're not careful. Here's how to keep your queries under 100ms.
1. Indexes are Mandatory
Never query on a field that isn't indexed. Use the .explain("executionStats") method to see if your query is doing a collection scan.
2. Schema Design (Embedding vs Referencing)
- Embed if the data is small and frequently read together.
- Reference if the data grows indefinitely or is accessed independently.
3. Aggregation Pipelines
Keep your stages efficient. Use $match and $sort as early as possible to reduce the number of documents passing through the pipeline.
Remember: Your application is only as fast as your slowest database query.