debugModerate
MongoDB slow queries from missing compound index order
Viewed 0 times
compound indexESR ruleexplainindex ordertotalDocsExaminedcovered query
nodejsdocker
Error Messages
Problem
MongoDB queries with multiple filter conditions are slow despite having individual indexes on each field. The compound index exists but the query still scans many documents.
Solution
Compound index field ORDER matters in MongoDB. Follow the ESR rule: Equality fields first, Sort fields second, Range fields last. Example: for query { status: 'active', createdAt: { $gte: date } } sorted by name, index should be { status: 1, name: 1, createdAt: 1 }. Use explain('executionStats') to verify. Check totalKeysExamined vs totalDocsExamined.
Why
MongoDB can only use a prefix of a compound index. The ESR order minimizes the index scan range. Equality narrows to exact matches, sort avoids in-memory sorting, range scans the minimum necessary keys.
Revisions (0)
No revisions yet.