A query plan cache stores a selected execution plan for a query shape so MongoDB can reuse a strategy instead of repeatedly evaluating every available option. During a trial phase, the query planner compares plans using actual query conditions and favors the plan that retrieves results efficiently with minimal work. section 7.1
Each query shape can occupy one of three cache states:
- Missing: no entry exists; MongoDB evaluates candidate plans, selects a winner, and creates an Inactive entry recording its work value. section 7.1
- Inactive: the query shape is recognized, but MongoDB reevaluates plans when queried again; an equally or more efficient plan can replace it as Active. section 7.1
- Active: the winning plan is currently used; performance degradation or increased work can cause reassessment and movement back to Inactive. section 7.1
Listing 7.1 Appending the MongoDB explain () method
db.collection.find(
{ yourField: "value" }
).explain() // Explain the default query planner information
db.collection.find(
{ yourField: "value" }
).explain(
"executionStats" // Explain the query execution statistics
)
db.collection.find(
{ yourField: "value" }
).explain(
"allPlansExecution" // Explain the query execution
➥plan with all possible query plans
)
Inspect a query’s chosen plan, execution statistics, or all candidate plans with MongoDB’s explain() verbosity modes. section 7.1.1
Use $planCacheStats to inspect a collection’s plan-cache information. The cache is purged after mongod restarts or shutdowns and after catalog operations such as dropping indexes or collections. Entries can also be cleared for a collection with PlanCache.clear() or selectively with PlanCache.clearPlansByQuery(). section 7.1.2 section 7.1.1
Inspecting a cached-plan candidate
Run db.collection.find({ yourField: "value" }).explain("executionStats") to see the selected plan and runtime statistics. An IXSCAN can locate matching index keys, while FETCH retrieves the corresponding documents; the output reports returned documents, execution time, examined keys, and examined documents. section 7.1.1
