Advanced Indexing
Beyond simple single-field and compound indexes, MongoDB offers specialized index types for specific data structures and use cases.
1. Multikey Indexes
If you index a field that contains an array, MongoDB automatically creates a Multikey Index. This allows you to query specific elements within the array efficiently.
// Indexing a "tags" array
db.products.createIndex({ tags: 1 })
2. Hashed Indexes
Hashed indexes maintain entries with hashes of the values of the indexed field. These are primarily used for Hashed Sharding to ensure even distribution of data across a cluster.
db.users.createIndex({ user_id: "hashed" })
3. Wildcard Indexes
Wildcard indexes support queries against unknown or arbitrary fields. This is perfect for collections with highly dynamic schemas.
db.products.createIndex({ "metadata.$**": 1 })
4. Partial Indexes
Matches only those documents that meet a specified filter expression. This saves space and improves write performance for sparse data.
// Only index documents where rating is greater than 5
db.restaurants.createIndex(
{ cuisine: 1, name: 1 },
{ partialFilterExpression: { rating: { $gt: 5 } } }
)
| Index Type | Best Use Case |
|---|
| Compound | Queries on multiple fixed fields. |
| Multikey | Efficiency with arrays. |
| TTL | Auto-deleting old data (logs, sessions). |
| Wildcard | Dynamic data structures with unpredictable keys. |
Pro Tip: Use the explain() method to verify that your query is actually using the index you created.