11. Partial and Sparse Indexes
A partial index includes only documents that satisfy a specified filter expression. It can reduce index size and focus the index on a frequently queried subset, such as active records or documents that have a particular state.
A sparse index omits documents that do not contain the indexed field. Sparse and partial indexes are not interchangeable: partial indexes support more expressive filtering criteria, subject to MongoDB's supported partial-filter expressions.
The query planner must be able to use the index without returning documents that should not match the query. Therefore, a query often needs to include conditions compatible with the partial filter before the partial index can be used safely.
Choose partial indexes when a subset is meaningful and common in the workload. Be cautious with sparse indexes when missing-field semantics are important.
db.users.createIndex(
{ emailNormalized: 1 },
{ partialFilterExpression: { active: true } }
);
// This query matches the partial filter.
db.users.find({ active: true, emailNormalized: "user@example.com" })
.explain("executionStats");- Partial indexes include documents matching a filter.
- Sparse indexes omit documents missing the indexed field.
- Query predicates must be compatible with a partial index.
- Use these indexes when a well-defined subset dominates the workload.
What is the purpose of a partial index?