5. Compound Index Prefixes

A compound index supports its leading field and leading combinations of fields. These are called index prefixes.

For an index { a: 1, b: 1, c: 1 }, useful prefixes include { a: 1 }, { a: 1, b: 1 }, and { a: 1, b: 1, c: 1 }. A query that filters only on b generally cannot use this index as efficiently as an index whose leading key is b.

A compound index may therefore support several related query patterns. This can reduce the number of separate indexes needed, but it does not mean every field combination is covered.

Do not assume a suffix field can be used as though it were the leading field. Verify behavior with the query planner, especially when predicates and sorts are involved.

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

// Aligns with the first field.
db.orders.find({ status: "delivered" });

// Aligns with the first two fields.
db.orders.find({ status: "delivered", customerId: 501 });

// Does not use the leading prefix in the same way.
db.orders.find({ customerId: 501 });
Key Takeaways
  • Compound indexes support leading prefixes.
  • Suffix-only filters may not benefit efficiently from the index.
  • Prefix reuse can reduce redundant indexes.
  • Confirm index use with explain output.
Knowledge Check

For an index { a: 1, b: 1, c: 1 }, which is a leading prefix?