MongoDB Indexing Strategies: ESR Rule, Explain Plans, and Performance Tuning
"MongoDB Indexing Strategies: ESR Rule, Explain Plans, and Performance Tuning" published: true published_at: "2026-11-20T09:00:00+05:30" description: "Master MongoDB indexing by diving deep into the Equality, Sort, Range (ESR) rule, analyzing explain executionStats to catch COLLSCAN, and managing index overhead." tags: [mongodb, database, backend, performance] ai_disclosure_level: some_ai…
MongoDB indexing is crucial for query performance. Without proper indexes, MongoDB must scan the entire collection, leading to slow responses as collections grow large. This article outlines key indexing strategies to optimize performance.
Single-field indexes index one field, allowing quick equality searches, sorting, and range queries. However, frequent writes can slow down as the index must be updated.
Compound indexes combine multiple fields, but the order matters. Follow the Equality, Sort, Range (ESR) rule: put equality fields first, then sorting, and finally range fields. For example, querying orders by status, price range, and sorted by creation date would use indexes on status, createdAt, and price.
To check if queries are using indexes, run .explain("executionStats") on a query. Look for IXSCAN in the output instead of COLLSCAN, which indicates index usage. Monitor metrics like totalDocsExamined vs nReturned and totalKeysExamined. A healthy ratio is close to 1:1, while high key or doc counts suggest inefficient queries.
Lastly, manage index storage. Too many indexes can exceed RAM, causing disk paging and slowdowns. Use $indexStats to identify unused indexes. Optimize index usage for fast, efficient queries.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to