Home / Databases / MongoDB

DatabasesCheat sheetAdvanced

MongoDB plan cache and query settings cheat sheet: replanning, unstable plans, index hints without code changes and query rejection

A query shape flips between a good and a bad index. Inspect the plan cache, read replanning evidence, and steer or block the shape with setQuerySettings on MongoDB 8.0 and later.

Deepak Bhardwaj8 min read

Applies toMongoDB 7.0 and 8.x; query settings need 8.0 or later on a replica set or sharded cluster

The same query takes 5 ms in the morning and 5 seconds at noon, with no deploy and no index change. explain() shows the good plan. The plan cache holds a different one. Use this sheet to prove it and hold the plan steady.

Symptom, cause, fix

Symptom Likely cause Fix
Slow in the app, fast in explain() Cached plan differs; explain ignores the cache Read $planCacheStats
Slow on one node only Plan cache is per mongod Compare members
Bursts of replanned:true Skewed values share one shape Better index, or query settings
Slow after restart or index change Cache emptied; all shapes replan at once Warm up; avoid peak-time DDL
CPU high, tiny result sets, many plans Too many candidate indexes Drop redundant indexes
One bad shape hurts everyone Unplanned query from a release reject: true

How an entry lives

State Meaning Next
Missing No entry for this key Candidates race; the winner is stored as Inactive
Inactive Placeholder with a works value; not used for planning A run with equal or lower works makes it Active
Active Used for matching queries If it performs much worse than expected, replan

works measures effort in the trial. When a cached plan needs far more work than recorded, the server replans. That check is why one skewed value (the tenant with 40 million documents) can replace a plan that suits every other value.

The cache is cleared by a restart and by any index create, drop or hide on the collection. Least recently used entries are evicted as well.

Identify the shape

Identifier Depends on
planCacheShapeHash (queryHash before 8.0) The shape only
planCacheKey Shape plus available indexes
queryShapeHash Query settings and query stats shape (8.0+)

Same shape hash with a different key means the index set changed.

Slow query log and profiler fields to look at:

# mongod log is JSON, one document per line
jq -c 'select(.msg=="Slow query")
  | {ns:.attr.ns, plan:.attr.planSummary, key:.attr.planCacheKey,
     replanned:.attr.replanned, reason:.attr.replanReason,
     keys:.attr.keysExamined, docs:.attr.docsExamined,
     n:.attr.nreturned, ms:.attr.durationMillis}' mongod.log | tail -20

Field presence varies by version and by query; missing ones print as null.

// Is a shape flipping plans? Needs the profiler on for this database
db.system.profile.aggregate([
  { $match: { ns: "shop.orders", op: "query" } },
  { $group: { _id: { key: "$planCacheKey", plan: "$planSummary" },
              n: { $sum: 1 }, avgMs: { $avg: "$millis" }, maxMs: { $max: "$millis" },
              replanned: { $sum: { $cond: ["$replanned", 1, 0] } } } },
  { $sort: { "_id.key": 1, maxMs: -1 } }
])

Two planSummary values under one key is an unstable plan.

Inspect the plan cache

// All entries, the most expensive first
db.orders.aggregate([
  { $planCacheStats: {} },
  { $project: { planCacheShapeHash: 1, planCacheKey: 1, isActive: 1, works: 1,
                timeOfCreation: 1, createdFromQuery: 1, estimatedSizeBytes: 1, host: 1 } },
  { $sort: { works: -1 } }
])

// One entry in full
db.orders.aggregate([
  { $planCacheStats: {} },
  { $match: { planCacheKey: "<KEY_FROM_LOG>" } }
])

// Sharded cluster, every data-bearing node (7.1+)
db.orders.aggregate([ { $planCacheStats: { allHosts: true } } ])
  • $planCacheStats must be the first stage and needs the planCacheRead privilege.
  • allHosts: true returns an error on a replica set; connect to each member instead.
  • version: 1 entries are the classic engine, 2 the slot-based engine. The slot-based entries carry fewer debug fields.
  • When total plan cache size passes 0.5 GB, new entries omit createdFromQuery, cachedPlan, creationExecStats and candidatePlanScores. Missing fields can mean cache bloat.

Count distinct shapes to spot generated queries:

db.orders.aggregate([
  { $planCacheStats: {} },
  { $group: { _id: "$planCacheShapeHash", entries: { $sum: 1 }, bytes: { $sum: "$estimatedSizeBytes" } } },
  { $sort: { entries: -1 } }, { $limit: 20 }
])

Clear entries

// One shape: query, projection, sort must match the shape
db.orders.getPlanCache().clearPlansByQuery({ status: "x", tenantId: 1 }, {}, { createdAt: -1 })

// Whole collection, this node only
db.orders.getPlanCache().clear()

Warning

Clearing is first aid. The next skewed query can cache the same bad plan. Clearing a whole collection at peak makes every shape run a fresh plan race.

Reproduce with the right value

db.orders.find({ tenantId: 42, status: "open" }).sort({ createdAt: -1 }).limit(50)
  .explain("allPlansExecution")

Run it for the heaviest and a typical tenant. Compare totalKeysExamined, totalDocsExamined and any SORT stage. If the best plan differs by value, no single cached plan is right. First try an index that serves both:

// Equality, then sort; limits work for both small and large tenants
db.orders.createIndex({ tenantId: 1, status: 1, createdAt: -1 })

Test removal of a rival index without losing it:

db.orders.hideIndex("status_1")      // planner ignores it, writes still maintain it
db.orders.unhideIndex("status_1")

Hiding or unhiding clears the collection's plan cache, so expect a short replanning burst.

Steer a shape with query settings (8.0+)

Cluster-wide, persistent across restarts, no application release needed. Not available on a standalone, or on Atlas M0 and Flex.

db.adminCommand({
  setQuerySettings: {
    find: "orders",
    filter: { tenantId: 42, status: "open" },
    sort: { createdAt: -1 },
    $db: "shop"
  },
  settings: {
    indexHints: [ {
      ns: { db: "shop", coll: "orders" },
      allowedIndexes: [ "tenantId_1_status_1_createdAt_-1" ]
    } ]
  }
})
  • Values don't matter; the shape does. The example covers every tenantId and status.
  • allowedIndexes restricts the candidates. It doesn't force an index, and a collection scan remains possible.
  • Settings override index hints sent by the application for the same shape.
  • A hash works as well: setQuerySettings: "<queryShapeHash>".
  • Other fields: queryFramework ("classic" or "sbe") and comment (8.0.4 and later).

Confirm it took effect. explain() shows a querySettings block, and the plan cache entry does too:

db.orders.find({ tenantId: 7, status: "open" }).sort({ createdAt: -1 }).explain()

List and remove:

db.getSiblingDB("admin").aggregate([ { $querySettings: {} } ])

db.adminCommand({ removeQuerySettings: "<queryShapeHash>" })

Caution

If you drop an index named in allowedIndexes, the settings stay behind and stop helping. Check $querySettings before every index drop.

Index filters

planCacheSetFilter is deprecated from 8.0. Filters live in memory on one node and vanish on restart. Use them only on older versions:

db.runCommand({
  planCacheSetFilter: "orders",
  query: { tenantId: 42, status: "open" },
  sort: { createdAt: -1 },
  indexes: [ { tenantId: 1, status: 1, createdAt: -1 } ]
})
db.runCommand({ planCacheListFilters: "orders" })

Run it on every member that serves the query.

Block a runaway shape

db.adminCommand({
  setQuerySettings: "<queryShapeHash>",
  settings: { reject: true, comment: "INC-1234 unindexed report, owner: platform" }
})

New matching queries fail; running ones continue, so end those separately:

db.currentOp({ "active": true, "ns": "shop.orders", "secs_running": { $gt: 30 } })
db.killOp(<opid>)

To lift the block, use removeQuerySettings. Setting only reject: false on an entry with nothing else in its settings returns an error.

Caution

Rejection is by shape, for every caller. If the checkout page and a bad report share a shape, both fail. Look at representativeQuery in $querySettings and the application names in the log before you reject.

Which tool when

Need Use
Wrong plan right now, unclear why Clear one shape, then investigate
Plan flips with skewed values Better compound index
Vendor application, no code access setQuerySettings with indexHints
You own the code and want it in review .hint() in the query
Runaway query in production reject: true plus killOp
Test an index drop hideIndex

Prevent it next time

  • Alert on the rate of replanned in slow query logs per namespace.
  • Remove redundant prefix indexes. Fewer candidates mean cheaper, steadier planning.
  • Keep query settings in source control with an owner and expiry date, and review them after each major upgrade.
  • Build and drop indexes off-peak, because each one empties that collection's plan cache.
  • Load-test with your largest tenant's data, not an even distribution.