An index prefix is a leading subset of the fields in a compound index, preserving their defined order. MongoDB can use each prefix to optimize matching queries. section 7.2.2
For the compound index { year: 1, type: 1, "imdb.rating": 1 }, the usable prefixes are:
- { year: 1 } supports queries by release year. section 7.2.2
- { year: 1, type: 1 } supports queries by release year and type. section 7.2.2
- { year: 1, type: 1, "imdb.rating": 1 } supports queries using all three fields. section 7.2.2
- Queries using type or imdb.rating without year do not match a prefix and may require a collection scan. section 7.2.2
Query and sort alignment
A compound index such as { runtime: 1, year: 1 } can support filtering runtime greater than 40 and sorting by runtime, then year. For sorting alone, align the sort fields with the index order. section 7.6.7
Listing 7.6 Creating a compound index on three fields
db.movies.createIndex(
{ year: 1, type: 1, "imdb.rating": 1 }
)
Create a three-field compound index whose successive leading fields form usable index prefixes. section 7.2.2
