In this lesson, you will learn how to boost your database performance by creating compound and multi-key indexes for complex document searches.
Beyond Single-Field Indexing
When your documents grow in complexity—especially when they contain arrays or nested objects—a simple index on one field often isn't enough. To keep your Node.js application fast, you need to tell your database exactly how to traverse your document structure using specific index strategies.
Compound Indexes
A compound index allows you to index multiple fields together. This is essential when your application frequently queries by two criteria simultaneously. For example, if you are searching for a user by both their lastName and their status, a compound index ensures the database doesn't have to scan every single document.
// Schema definition for a compound index
userSchema.index({ lastName: 1, status: 1 });
The order matters here: the database will sort by the first field (lastName), and then by the second (status).
Multi-Key Indexes
In NoSQL document databases, you often store arrays inside documents, such as an array of tags on a blog post. If you want to find posts that match a specific tag, a multi-key index is your best friend. When you create an index on an array field, the database automatically creates a separate index entry for each element in the array.
// Indexing an array field creates a Multi-Key index
postSchema.index({ tags: 1 });
This allows the database to "drill into" the array and find the exact documents containing a specific tag in near-constant time, rather than performing an expensive full-collection scan.
Choosing Your Strategy
When deciding which index to use, always look at your find() queries. If you are filtering by multiple fields, use a compound index. If you are frequently searching inside embedded arrays, use a multi-key index. Remember that while indexes make reads faster, they do consume disk space and can slightly slow down write operations (as the index must be updated with every insert or update). Use them strategically for the paths your users visit most often.
Key Takeaway: Use compound indexes to satisfy queries filtering by multiple document fields, and use multi-key indexes to perform high-speed lookups on elements nested within arrays.