A partial index on a collection is an index that only applies to the documents that satisfy the partialFilterExpression query.
We'll use our familiar books collection, as follows:
> db.books.createIndex(
{ price: 1, name: 1 },
{ partialFilterExpression: { price: { $gt: 30 } } }
)
Using this, we can have an index for just the books that have a price greater than 30. The advantage of partial indexes is that they are more lightweight in creation and maintenance, and use less storage.
The partialFilterExpression filter supports the following operators:
- Equality expressions (that is, field: value, or using the $eq operator)
- The $exists: true expression
- The $gt, $gte, $lt, and $lte expressions
- $type expressions
- The $and operator, at the top level only
Partial indexes will only be used if the query can be satisfied as a whole by the partial index.
If our query matches or is more restrictive than the partialFilterExpression filter, then the partial index will be used. If the results may not be contained in the partial index, then the index will be totally ignored.
partialFilterExpression does not need to be a part of the sparse index fields. The following index is a valid sparse index:
> db.books.createIndex({ name: 1 },{ partialFilterExpression: { price: { $gt: 30 } } })
To use this partial index, however, we need to query for both name and price equal to or greater than 30.