MongoDB is a highly flexible document database, but as your collections scale to millions of records, query performance can degrade rapidly. If MongoDB has to scan every single document in a collection (a full collection scan or COLLSCAN) to satisfy a query, response times will balloon from milliseconds to seconds. Creating compound indexes is one of the most powerful optimization strategies to speed up multi-field lookups.
In MongoDB, an index is a sorted data structure that stores a small portion of the collection's data in an easy-to-traverse B-tree format. While a single-field index sorts documents by one field, a compound index supports queries that filter or sort by multiple fields. For example, if you frequently query user credits based on their status and department, you can define a compound index:
// Schema setup in Mongoose
userSchema.index({ status: 1, department: 1 });
The ordering of the fields in a compound index is critical. MongoDB sorts the keys first by the first field (status), and then by the second field (department).
To design compound indexes that satisfy both filter constraints and sorting orders, always follow the ESR rule:
- [object Object]
// Index designed for query: { category: 'Coding', rating: { $gt: 4 } } sort by { createdAt: -1 }
blogSchema.index({ category: 1, createdAt: -1, rating: 1 });
Never guess if your indexes are working. Use MongoDB's explain() command to view query plans and execution statistics:
const explainPlan = await Blog.find({ category: 'Coding' })
.sort({ createdAt: -1 })
.explain('executionStats');
console.log(explainPlan.executionStats);
Look for these indicators:
- [object Object]
Designing smart compound indexes ensures MongoDB retrieves documents in constant time, even as database size grows. Adhering to the ESR rule and verifying index execution paths using explain() keeps backend services responsive and server loads minimal.