18. Index Intersection and Why Compound Indexes Still Matter

MongoDB may be able to combine multiple indexes for some queries, a behavior known as index intersection. However, index intersection is not a reason to avoid designing compound indexes for frequent query patterns.

A suitable compound index may provide more efficient filtering and sorting in one ordered structure. Intersecting separate indexes may involve additional work and may not satisfy the sort requirement.

If a query frequently filters by both status and customerId, test an index such as { status: 1, customerId: 1 } against separate indexes. Consider all query shapes that need support before choosing a design.

Code Example
db.orders.createIndex({ status: 1 });
db.orders.createIndex({ customerId: 1 });

// Compare against a compound candidate in a test environment.
db.orders.createIndex({ status: 1, customerId: 1 });

db.orders.find({ status: "delivered", customerId: 501 })
  .explain("executionStats");
Key Takeaways
  • Index intersection can combine separate indexes for some queries.
  • A compound index may better support frequent combined predicates.
  • Sorting requirements can affect which plan is best.
  • Compare alternatives using explain and workload benchmarks.
Knowledge Check

Does the existence of index intersection mean compound indexes are unnecessary?