About query plan caching

I know query plan is stored in cache.

But if a better query plan appears, I wonder if the previous plan will be erased or both.

I hope you will find the following useful.


I saw that and asked the question.

Hi @Kim_Hakseon,

Per the documentation that @steevej referenced, a query plan that is Active can move to an Inactive state in the cache if there is a better performing plan:

The planner also evaluates the entry’s performance and if its works value no longer meets the selection criterion, it will transition to Inactive state.

The query cache is also affected by catalog operations like index changes and collection drops (see: Plan Cache Flushes).

There have been some changes to query plan caching in successive MongoDB versions, so if you are using an older release series of MongoDB please select the relevant version of the manual from the selection drop-down near the top left of the Query Plans page. The description above is applicable to MongoDB 4.2 and 4.4 (which added states for plan cache entries), but all modern versions of MongoDB have a query replanning mechanism.


So, if a better plan appears in version 4.2, is it okay to think that the previous plan will be erased from the cache?

Hi @Kim_Hakseon,

In general you should expect that a cached plan will automatically be replaced if a more efficient plan is available.

The plan cache in MongoDB 4.2+ associates a state for each cache entry to provide more nuanced replanning behaviour than the outright eviction of prior versions. With this version of the plan cache, inactive cache entries (with their associated cost) are removed from the plan cache on a Least Recently Used (LRU) basis.

For comparison, see the query plan flow chart for MongoDB 4.0: https://docs.mongodb.com/v4.0/core/query-plans/.


Thank you~👍

It helped me a lot.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.