- Indexes >
- Index Intersection
Index Intersection¶
On this page
MongoDB can use the intersection of multiple indexes to fulfill queries. In general, each index intersection involves two indexes; however, MongoDB can employ multiple/nested index intersections to resolve a query.
To illustrate index intersection, consider a collection orders
that
has the following indexes:
MongoDB can use the intersection of the two indexes to support the following query:
To determine if MongoDB used index intersection, run
explain()
; the results of explain() will include either an
AND_SORTED
stage or an AND_HASH
stage.
Index Prefix Intersection¶
With index intersection, MongoDB can use an intersection of either the entire index or the index prefix. An index prefix is a subset of a compound index, consisting of one or more keys starting from the beginning of the index.
Consider a collection orders
with the following indexes:
To fulfill the following query which specifies a condition on both the
qty
field and the status
field, MongoDB can use the
intersection of the two indexes:
Index Intersection and Compound Indexes¶
Index intersection does not eliminate the need for creating compound indexes. However, because both the list order (i.e. the order in which the keys are listed in the index) and the sort order (i.e. ascending or descending), matter in compound indexes, a compound index may not support a query condition that does not include the index prefix keys or that specifies a different sort order.
For example, if a collection orders
has the following compound
index, with the status
field listed before the ord_date
field:
The compound index can support the following queries:
But not the following two queries:
However, if the collection has two separate indexes:
The two indexes can, either individually or through index intersection, support all four aforementioned queries.
The choice between creating compound indexes that support your queries or relying on index intersection depends on the specifics of your system.
Index Intersection and Sort¶
Index intersection does not apply when the sort()
operation requires an index completely separate from the query
predicate.
For example, the orders
collection has the following indexes:
MongoDB cannot use index intersection for the following query with sort:
That is, MongoDB does not use the { qty: 1 }
index for the query,
and the separate { status: 1 }
or the { status: 1, ord_date: -1
}
index for the sort.
However, MongoDB can use index intersection for the following query
with sort since the index { status: 1, ord_date: -1 }
can fulfill
part of the query predicate.