What are partial indexes in MongoDB?
Answer
Partial indexes (MongoDB 3.2+) index only the documents in a collection that meet a specified filter expression, rather than all documents. More flexible and expressive than sparse indexes. Creating a partial index: db.users.createIndex({ email: 1 }, { partialFilterExpression: { status: "active" } }) — only indexes users where status is "active". Partial filter expressions support: equality ($eq), comparison ($gt, $gte, $lt, $lte), $exists, $type, $and (top-level only). Benefits over sparse indexes: (1) Can specify any filter condition, not just field existence; (2) Significantly reduces index size for selective conditions; (3) Faster index maintenance (fewer entries to update/insert); (4) Useful for frequently queried subsets. Query must include filter conditions: to use a partial index, the query must include a condition guaranteed to match the partial filter expression. db.users.find({ email: "alice@example.com", status: "active" }) — will use the partial index. db.users.find({ email: "alice@example.com" }) — will NOT use the partial index (might return inactive users, which aren't in the index). Partial unique index: enforce uniqueness only among documents matching the filter: db.orders.createIndex({ userId: 1 }, { unique: true, partialFilterExpression: { status: "active" } }) — allows multiple completed orders per user but only one active order. vs Sparse: sparse only handles field existence; partial handles any condition.
Previous
What is MongoDB's read concern?
Next
What is the MongoDB aggregation $bucket and $bucketAuto stage?