Skip to content

MongoDB partial indexes for hot-path queries

Use MongoDB partial indexes to index only the documents a query actually matches — smaller indexes, faster writes, fewer collection scans on the unhappy path.

A partial index in MongoDB only indexes documents that match a filter expression. If you query active users out of a collection where 99% of rows are inactive, indexing only the active ones cuts index size by 100× and the planner still uses it for queries that include the filter as a predicate. This is one of the highest-leverage tuning levers in MongoDB and one of the most under-used.

How to verify

Create a partial index, prove the planner uses it, and compare index sizes:

mongosh --host primary.example.internal:27017
use shop
db.users.createIndex(
  { lastSeenAt: -1 },
  { partialFilterExpression: { status: "active" } })
db.users.totalIndexSize()
db.users.find({ status: "active" }).sort({ lastSeenAt: -1 }).limit(10).explain("executionStats")

The explain output should show IXSCAN against the partial index when the filter expression matches the query predicate. If the query omits status: "active", the planner falls back to a different index or a COLLSCAN — the partial index is invisible to queries that do not include its filter.

What’s happening

A partial index has a partialFilterExpression — a query subset (only $eq, $gt, $lt, $gte, $lte, $type, $exists with value true, and $and at the top level are allowed). The index stores only entries for documents that match the expression. Writes that produce a non-matching document are not indexed at all — saving CPU and disk on every insert and update.

The planner can only use the partial index for a query whose predicates imply the filter expression. In practice, this means the query must include the filter’s conditions in its match. db.users.find({ status: "active", email: "x@example.com" }) can use the partial index above; db.users.find({ email: "x@example.com" }) cannot, because the planner cannot prove the result set is a subset of indexed documents.

Partial indexes generalize the older sparse: true option. A sparse index excludes documents where the indexed field is missing, but offers no other predicate. A partial index can express the same thing (partialFilterExpression: { fieldName: { $exists: true } }) and much more — arbitrary equality and range conditions on multiple fields.

The procedure

  1. Identify the hot subset. Look at the dominant $match in your slow queries and find the predicate that filters out most documents.

    db.system.profile.aggregate([
      { $match: { "command.find": "users" } },
      { $project: { filter: "$command.filter", millis: 1 } },
      { $sort: { millis: -1 } },
      { $limit: 20 }
    ])
  2. Create the partial index with the filter as partialFilterExpression. Match the predicates your hot query uses.

    db.users.createIndex(
      { lastSeenAt: -1, email: 1 },
      { partialFilterExpression: { status: "active", tenantId: { $exists: true } } }
    )
  3. Confirm the planner uses it. Run the hot query with explain and look for the new index name in winningPlan.

    db.users.find({ status: "active", tenantId: 42 }).sort({ lastSeenAt: -1 }).explain("executionStats")
  4. Drop the larger sibling index if it exists. A partial index that covers the hot path makes the full index redundant for the same query — but verify with $indexStats first that nothing else relies on it.

    db.users.aggregate([{ $indexStats: {} }])
    db.users.dropIndex("ix_lastSeenAt")
  5. Layer unique constraints on partial indexes. A unique partial index enforces uniqueness only among matching documents — useful for soft-delete tables where archived rows can collide on a previously-unique key.

    db.users.createIndex(
      { email: 1 },
      { unique: true, partialFilterExpression: { deleted: { $ne: true } } }
    )

Operational notes

  • The planner is strict about implication. A query that uses $in for the field in the filter expression may not match — $in: ["active"] does not equal $eq: "active" for partial-index purposes. Test with explain on the exact query shapes the application sends.
  • Updating the indexed field can move documents in and out of the index. A user changing from inactive to active causes an index insert; the opposite causes an index delete. Hot-path status changes are still index writes.
  • partialFilterExpression is immutable. You cannot alter it; you must drop and rebuild the index, which means a window where queries fall back to a worse plan.
  • Sparse indexes are still relevant for unique constraints with optional fields. A sparse: true unique index on email allows multiple documents without an email — useful in some schemas where the equivalent partial expression is awkward.
  • Background index builds on large collections take hours. Time the build during a window with low write rate; index builds compete with writes for storage IOPS.

Stack Harbor uses partial indexes to trim 50-90% of the index footprint on collections where the hot working set is a small fraction of the total documents. We design the filter expression against the dominant query, validate planner usage with explain, and retire the now-redundant full indexes. See /en/services/managed-operations/ for the engagement model around ongoing MongoDB tuning.