Database Manual / Reference / Query Language / Aggregation Stages

$planCacheStats

Definition定义

$planCacheStats

Returns plan cache information for a collection. The stage returns a document for each plan cache entry.返回集合的计划缓存信息。该阶段为每个计划缓存条目返回一个文档。

The $planCacheStats stage must be the first stage in the pipeline. The stage has the following syntax:$planCacheStats阶段必须是管道中的第一阶段。该阶段具有以下语法:

{
$planCacheStats: {
allHosts: <boolean>
}
}

The $planCacheStats aggregation stage has the following options:$planCacheStats聚合阶段有以下选项:

Option选项Description描述
allHosts

Configures how the $planCacheStats aggregation stage targets nodes in a sharded cluster.配置$planCacheStats聚合阶段如何以分片集群中的节点为目标。

  • If true, mongos broadcasts the $planCacheStats aggregation stage to all nodes (primary and secondaries) for each affected shard that contains one or more chunks from the target collection.如果为truemongos会将$planCacheStats聚合阶段广播到每个受影响分片的所有节点(主节点和次节点),这些分片包含目标集合中的一个或多个块。
  • If false, the $planCacheStats aggregation stage follows the Read Preference and only retrieves the plan cache from the targeted replica set primary.如果为false$planCacheStats聚合阶段将遵循读取首选项,并且仅从目标副本集主副本中检索计划缓存。

Replica sets and standalone servers return an error during pipeline parsing if allHosts is set to true. The option is only available to sharded clusters.如果allHosts设置为true,则副本集和单机版服务器在管道解析过程中会返回错误。该选项仅适用于分片集群。

Default: 默认值:false

New in version 7.1.在版本7.1中新增。

Considerations注意事项

Pipeline管道

$planCacheStats must be the first stage in an aggregation pipeline.必须是聚合管道的第一阶段。

Restrictions限制

  • $planCacheStats is not allowed in:不允许用于:

  • $planCacheStats requires read concern level "local".需要阅读"local"关注级别。

Access Control访问控制

On systems running with authorization, the user must have the planCacheRead privilege for the collection.授权运行的系统上,用户必须具有该集合的planCacheRead权限。

Redaction编辑

When using Queryable Encryption, the $planCacheStats stage omits operations against encrypted collections, even though the operations are cached as normal.当使用可查询加密时,$planCacheStats阶段会省略对加密集合的操作,即使这些操作是正常缓存的。

Read Preference读取首选项

When the allHosts option is set to false, $planCacheStats follows the read preference in selecting the host(s) from which to return the plan cache information.allHosts选项设置为false时,$planCacheStats在选择从中返回计划缓存信息的主机时会遵循读取首选项

Applications may target different members of a replica set. As such, each replica set member might receive different read commands and have plan cache information that differs from other members. 应用程序可能针对副本集的不同成员。因此,每个副本集成员可能会收到不同的读取命令,并具有与其他成员不同的计划缓存信息。Nevertheless, running $planCacheStats on a replica set or a sharded cluster obeys the normal read preference rules. 然而,在副本集或分片集群上运行$planCacheStats会遵守正常的读取首选项规则。That is, on a replica set, the operation gathers plan cache information from just one member of replica set, and on a sharded cluster, the operation gathers plan cache information from just one member of each shard replica set.也就是说,在副本集上,操作仅从副本集的一个成员集合计划缓存信息,而在分片集群上,操作只从每个分片副本集的某个成员集合规划缓存信息。

Output输出

Changed in version 7.0.在版本7.0中的更改。

The output of $planCacheStats depends on the query engine used to complete the query. The value of the version field of the $planCacheStats indicates which query engine was used:$planCacheStats的输出取决于用于完成查询的查询引擎。$planCacheStatsversion字段的值指示使用了哪个查询引擎:

Classic Execution Engine经典执行引擎

For queries that use the classic execution engine, $planCacheStats returns a document similar to the following:对于使用经典执行引擎的查询,$planCacheStats返回一个类似于以下内容的文档:

{
"version" : 1,
"createdFromQuery" : <document>,
"planCacheShapeHash" : <hexadecimal string>,
"planCacheKey" : <hexadecimal string>,
"isActive" : <boolean>,
"works" : <NumberLong>,
"cachedPlan" : {
"stage" : <STAGE1>,
"filter" : <document>,
"inputStage" : {
"stage" : <STAGE2>,
...
}
},
"timeOfCreation" : <date>,
"creationExecStats" : [ // Exec Stats Document for each candidate plan
{
"nReturned" : <num>,
"executionTimeMillisEstimate" : <num>,
"totalKeysExamined" : <num>,
"totalDocsExamined" :<num>,
"executionStages" : {
"stage" : <STAGE A>,
...
"inputStage" : {
"stage" : <STAGE B>,
...
}
}
},
...
],
"candidatePlanScores" : [
<number>,
...
],
"indexFilterSet" : <boolean>,
"estimatedSizeBytes" : <num>,
"querySettings" : <document>,
"host" : <string>,
"shard" : <string>
}

Each document includes various query plan and execution stats, including:每个文档都包含各种查询计划和执行统计数据,包括:

Field字段Description描述
version

A number that indicates the query engine used to complete the query.一个数字,表示用于完成查询的查询引擎。

createdFromQuery

A document that contains the specific query that resulted in this cache entry. For example:包含导致此缓存条目的特定查询的文档。例如:

{
"query" : <document>,
"sort" : <document>,
"projection" : <document>
}
isActive

A boolean that indicates whether the entry is active or inactive.一个布尔值,指示条目是活动的还是非活动的。

  • If active, the query planner is currently using the entry to generate query plans.如果处于活动状态,则查询计划器当前正在使用该条目生成查询计划。
  • If inactive, the query planner is not currently using the entry to generate query plans.如果处于非活动状态,则查询计划器当前未使用该条目生成查询计划。

See Plan Cache Entry State.请参见计划缓存条目状态

planCacheShapeHash

A hexadecimal string that represents the hash of the query shape. See explain.queryPlanner.planCacheShapeHash.表示查询形状哈希值的十六进制字符串。请参阅explain.queryPlanner.planCacheShapeHash

Starting in MongoDB 8.0, the existing queryHash field is duplicated in a new field named planCacheShapeHash. If you're using an earlier MongoDB version, you'll only see the queryHash field. 从MongoDB 8.0开始,现有的queryHash字段被复制到一个名为planCacheShapeHash的新字段中。如果你使用的是早期的MongoDB版本,你只会看到queryHash字段。Future MongoDB versions will remove the deprecated queryHash field, and you'll need to use the planCacheShapeHash field instead.未来的MongoDB版本将删除弃用的queryHash字段,您将需要使用planCacheShapeHash字段。

planCacheKey

A hexadecimal string that represents the hash of the key used to find the plan cache entry associated with this query. The plan cache key is a function of both the plan cache query shape and the currently available indexes for that shape. 一个十六进制字符串,表示用于查找与此查询关联的计划缓存条目的键的哈希值。计划缓存键是计划缓存查询形状和该形状的当前可用索引的函数。See explain.queryPlanner.planCacheKey.请参阅explain.queryPlanner.planCacheKey

cachedPlan

The details of the cached plan. The fields included in the cachedPlan vary based on whether the query was completed using the classic engine or the slot-based query execution engine. 缓存计划的详细信息。cachedPlan中包含的字段会根据查询是使用经典引擎还是基于插槽的查询执行引擎完成而有所不同。For more information on query plans, see explain.queryPlanner.有关查询计划的更多信息,请参阅explain.queryPlanner

worksThe number of "work units" performed by the query execution plan during the trial period when the query planner evaluates candidate plans. 查询计划器评估候选计划时,查询执行计划在试用期内执行的“工作单元”数量。For more information, see explain.executionStats.executionStages.works.有关更多信息,请参阅explain.executionStats.executionStages.works
timeOfCreationTime of creation for the entry.条目的创建时间。
creationExecStats

An array of execution stats documents. The array contains a document for each candidate plan.一系列执行统计文档。该数组包含每个候选计划的文档。

For details on the execution stats, see explain.executionStats.有关执行统计信息的详细信息,请参阅explain.executionStats

candidatePlanScores

An array of scores for the candidate plans listed in the creationExecStats array.creationExecStats数组中列出的候选计划的分数数组。

indexFilterSetA boolean that indicates whether an index filter exists for the plan cache query shape.一个布尔值,指示计划缓存查询形状是否存在索引筛选器
estimatedSizeBytesThe estimated size in bytes of a plan cache entry.计划缓存条目的估计大小(以字节为单位)。
querySettings

New in version 8.0.在版本8.0中新增。

A document that contains query settings previously set using setQuerySettings:包含以前使用setQuerySettings设置的查询设置的文档:

querySettings: {
indexHints: [ {
ns: { db: <string>, coll: <string> },
allowedIndexes: <array>
}, ... ],
queryFramework: <string>
}

querySettings fields:领域:

Field字段Type类型Description描述
indexHints.nsdocument文档

Namespace for index hints.索引提示的命名空间。

dbstring字符串Name of the database for index hints.索引提示数据库的名称。
collstring字符串Name of the collection for index hints.索引提示集合的名称。
indexHints.allowedIndexesarray数组Array of indexes for index hints. For more details, see Indexes and hint().索引提示的索引数组。有关更多详细信息,请参阅索引hint()
queryFrameworkstring字符串

Query framework查询框架 string can be:字符串可以是:

host

The hostname and port of the mongod instance from which the plan cache information was returned.返回计划缓存信息的mongod实例的主机名和端口。

When run on a sharded cluster, the operation returns plan cache entry information from a single member in each shard replica set. This member is identified with the shard and host fields. 在分片集群上运行时,该操作从每个分片副本集中的单个成员返回计划缓存条目信息。此成员由分片主机字段标识。See also Redaction.另请参见编辑

shard

The name of the shard from which $planCacheStats retrieved the cache entry.$planCacheStats从中检索缓存条目的分片的名称。

Only available if run on a sharded cluster.仅在分片集群上运行时可用。

Slot-Based Query Execution Engine基于插槽的查询执行引擎

For queries that use the slot-based query execution engine, $planCacheStats returns a document similar to the following:对于使用基于槽的查询执行引擎的查询,$planCacheStats返回一个类似于以下内容的文档:

{
"version" : 2,
"planCacheShapeHash" : <hexadecimal string>,
"planCacheKey" : <hexadecimal string>,
"isActive" : <boolean>,
"works" : <NumberLong>,
"cachedPlan" : {
"slots" : <string>,
"stages": <string>
},
"indexFilterSet" : <boolean>,
"estimatedSizeBytes" : <num>,
"querySettings" : <document>,
"host" : <string>
}

Each document includes various query plan and execution stats, including:每个文档都包含各种查询计划和执行统计数据,包括:

Field字段Description描述
version

A number that indicates the query engine used to complete the query.一个数字,表示用于完成查询的查询引擎。

planCacheShapeHash

A hexadecimal string that represents the hash of the query shape. 表示查询形状哈希值的十六进制字符串。See explain.queryPlanner.planCacheShapeHash.请参阅解释explain.queryPlanner.planCacheShapeHash

Starting in MongoDB 8.0, the existing queryHash field is duplicated in a new field named planCacheShapeHash. If you're using an earlier MongoDB version, you'll only see the queryHash field. 从MongoDB 8.0开始,现有的queryHash字段被复制到一个名为planCacheShapeHash的新字段中。如果你使用的是早期的MongoDB版本,你只会看到queryHash字段。Future MongoDB versions will remove the deprecated queryHash field, and you'll need to use the planCacheShapeHash field instead.未来的MongoDB版本将删除弃用的queryHash字段,您将需要使用planCacheShapeHash字段。

planCacheKey

A hexadecimal string that represents the hash of the key used to find the plan cache entry associated with this query. 一个十六进制字符串,表示用于查找与此查询关联的计划缓存条目的键的哈希值。The plan cache key is a function of both the plan cache query shape and the currently available indexes for that shape. 计划缓存键是计划缓存查询形状和该形状的当前可用索引的函数。See explain.queryPlanner.planCacheKey.请参阅explain.queryPlanner.planCacheKey

isActive

A boolean that indicates whether the entry is active or inactive.一个布尔值,指示条目是活动的还是非活动的。

  • If active, the query planner is currently using the entry to generate query plans.如果处于活动状态,则查询计划器当前正在使用该条目生成查询计划。
  • If inactive, the query planner is not currently using the entry to generate query plans.如果处于非活动状态,则查询计划器当前未使用该条目生成查询计划。

See Plan Cache Entry State.请参见计划缓存条目状态

works

The number of "work units" performed by the query execution plan during the trial period when the query planner evaluates candidate plans. 查询计划器评估候选计划时,查询执行计划在试用期内执行的“工作单元”数量。For more information, see explain.executionStats.executionStages.works.有关更多信息,请参阅explain.executionStats.executionStages.works

cachedPlan

The details of the cached plan. The fields included in the cachedPlan vary based on whether the query was completed using the classic engine or the slot-based query execution engine. 缓存计划的详细信息。cachedPlan中包含的字段会根据查询是使用经典引擎还是基于插槽的查询执行引擎完成而有所不同。For more information on query plans, see explain.queryPlanner.有关查询计划的更多信息,请参阅explain.queryPlanner

indexFilterSet

A boolean that indicates whether an index filter exists for the plan cache query shape.一个布尔值,指示计划缓存查询形状是否存在索引筛选器

estimatedSizeBytes

The estimated size in bytes of a plan cache entry.计划缓存条目的估计大小(以字节为单位)。

querySettings

New in version 8.0.在版本8.0中新增。

A document that contains query settings previously set using setQuerySettings:包含以前使用setQuerySettings设置的查询设置的文档:

querySettings: {
indexHints: [ {
ns: { db: <string>, coll: <string> },
allowedIndexes: <array>
}, ... ],
queryFramework: <string>
}

querySettings fields:字段:

Field字段Type类型Description描述
indexHints.nsdocument文档

Namespace for index hints.索引提示的命名空间。

dbstring字符串Name of the database for index hints.索引提示数据库的名称。
collstring字符串Name of the collection for index hints.索引提示集合的名称。
indexHints.allowedIndexesarray数组Array of indexes for index hints. For more details, see Indexes and hint().索引提示的索引数组。有关更多详细信息,请参阅索引hint()
queryFrameworkstring字符串

Query framework查询框架 string can be:字符串可以是:

host

The hostname and port of the mongod instance from which the plan cache information was returned.返回计划缓存信息的mongod实例的主机名和端口。

When run on a sharded cluster, the operation returns plan cache entry information from a single member in each shard replica set. This member is identified with the shard and host fields. See also Redaction.在分片集群上运行时,该操作从每个分片副本集中的单个成员返回计划缓存条目信息。此成员由分片主机字段标识。另请参见编辑

Examples示例

MongoDB Shell

The examples in this section use the following orders collection:本节中的示例使用以下orders集合:

db.orders.insertMany( [
{ "_id" : 1, "item" : "abc", "price" : Decimal128("12"), "quantity" : 2, "type": "apparel" },
{ "_id" : 2, "item" : "jkl", "price" : Decimal128("20"), "quantity" : 1, "type": "electronics" },
{ "_id" : 3, "item" : "abc", "price" : Decimal128("10"), "quantity" : 5, "type": "apparel" },
{ "_id" : 4, "item" : "abc", "price" : Decimal128("8"), "quantity" : 10, "type": "apparel" },
{ "_id" : 5, "item" : "jkl", "price" : Decimal128("15"), "quantity" : 15, "type": "electronics" }
] )

Create the following indexes on the collection:在集合上创建以下索引:

db.orders.createIndex( { item: 1 } );
db.orders.createIndex( { item: 1, quantity: 1 } );
db.orders.createIndex( { quantity: 1 } );
db.orders.createIndex( { quantity: 1, type: 1 } );
db.orders.createIndex(
{ item: 1, price: 1 },
{ partialFilterExpression: { price: { $gte: Decimal128("10")} } }
);

Note

Index { item: 1, price: 1 } is a partial index and only indexes documents with price field greater than or equal to Decimal128("10").索引{ item: 1, price: 1 }部分索引,仅对price字段大于或等于Decimal128("10")的文档进行索引。

Run some queries against the collection:对集合运行一些查询:

db.orders.find( { item: "abc", price: { $gte: Decimal128("10") } } )
db.orders.find( { item: "abc", price: { $gte: Decimal128("5") } } )
db.orders.find( { quantity: { $gte: 20 } } )
db.orders.find( { quantity: { $gte: 5 }, type: "apparel" } )

The preceding queries are completed using the slot-based query execution engine.前面的查询是使用基于槽的查询执行引擎完成的。

Return Information for All Entries in the Query Cache返回查询缓存中所有条目的信息

The following aggregation pipeline uses $planCacheStats to return information about the plan cache entries for the collection:以下聚合管道使用$planCacheStats返回有关集合的计划缓存条目的信息:

db.orders.aggregate( [
{ $planCacheStats: { } }
] )

Output:输出:

[
{ // Plan Cache Entry 1
version: '2',
planCacheShapeHash: '478AD696',
planCacheKey: '21AE23AD',
isActive: true,
works: Long("7"),
timeOfCreation: ISODate("2023-05-22T20:33:49.031Z"),
cachedPlan: {
...
},
indexFilterSet: false,
isPinned: false,
estimatedSizeBytes: Long("8194"),
host: 'mongodb1.example.net:27018'
},
{ // Plan Cache Entry 2
version: '2',
planCacheShapeHash: '3D8AFDC6',
planCacheKey: '1C2C4360',
isActive: true,
works: Long("6"),
timeOfCreation: ISODate("2023-05-22T20:33:50.584Z"),
cachedPlan: {
...
},
indexFilterSet: false,
isPinned: false,
estimatedSizeBytes: Long("11547"),
host: 'mongodb1.example.net:27018'
},
{ // Plan Cache Entry 3
version: '2',
planCacheShapeHash: '27285F9B',
planCacheKey: '20BB9404',
isActive: true,
works: Long("1"),
timeOfCreation: ISODate("2023-05-22T20:33:49.051Z"),
cachedPlan: {
...
},
indexFilterSet: false,
isPinned: false,
estimatedSizeBytes: Long("7406"),
host: 'mongodb1.example.net:27018'
},
{ // Plan Cache Entry 4
version: '2',
planCacheShapeHash: '478AD696',
planCacheKey: 'B1435201',
isActive: true,
works: Long("5"),
timeOfCreation: ISODate("2023-05-22T20:33:49.009Z"),
cachedPlan: {
...
},
indexFilterSet: false,
isPinned: false,
estimatedSizeBytes: Long("7415"),
host: 'mongodb1.example.net:27018'
}
],

Warning

Starting in MongoDB 8.0, the existing queryHash field is duplicated in a new field named planCacheShapeHash. 从MongoDB 8.0开始,现有的queryHash字段被复制到一个名为planCacheShapeHash的新字段中。If you're using an earlier MongoDB version, you'll only see the queryHash field. Future MongoDB versions will remove the deprecated queryHash field, and you'll need to use the planCacheShapeHash field instead.如果你使用的是早期的MongoDB版本,你只会看到queryHash字段。未来的MongoDB版本将删除弃用的queryHash字段,您将需要使用planCacheShapeHash字段。

See also planCacheKey.另请参见planCacheKey

Find Cache Entry Details for a Query Hash查找查询哈希的缓存条目详细信息

To return plan cache information for a particular query hash, the $planCacheStats stage can be followed by a $match on the planCacheKey field.要返回特定查询哈希的计划缓存信息,可以在$planCacheStats阶段之后在planCacheKey字段上进行$match

The following aggregation pipeline uses $planCacheStats followed by a $match stage to return specific information for a particular query hash:以下聚合管道使用$planCacheStats,后面是$match阶段,返回特定查询哈希的特定信息:

db.orders.aggregate( [
{ $planCacheStats: { } },
{ $match: { planCacheKey: "B1435201"} }
] )

Output:输出:

[
{
version: '2',
planCacheShapeHash: '478AD696',
planCacheKey: 'B1435201',
isActive: true,
works: Long("5"),
timeOfCreation: ISODate("2023-05-22T20:33:49.009Z"),
cachedPlan: {
slots: '$$RESULT=s11 env: { s3 = 1684787629009 (NOW), s6 = Nothing, s5 = Nothing, s1 = TimeZoneDatabase(Asia/Kuwait...Etc/UCT) (timeZoneDB), s10 = {"item" : 1, "price" : 1}, s2 = Nothing (SEARCH_META) }',
stages: '[2] nlj inner [] [s4, s7, s8, s9, s10] \n' +
' left \n' +
' [1] cfilter {(exists(s5) && exists(s6))} \n' +
' [1] ixseek s5 s6 s9 s4 s7 s8 [] @"358822b7-c129-47b7-ad7f-40017a51b03c" @"item_1_price_1" true \n' +
' right \n' +
' [2] limit 1 \n' +
' [2] seek s4 s11 s12 s7 s8 s9 s10 none none [] @"358822b7-c129-47b7-ad7f-40017a51b03c" true false \n'
},
indexFilterSet: false,
isPinned: false,
estimatedSizeBytes: Long("7415"),
host: 'mongodb1.example.net:27018'
}
]

Warning

Starting in MongoDB 8.0, the existing queryHash field is duplicated in a new field named planCacheShapeHash. 从MongoDB 8.0开始,现有的queryHash字段被复制到一个名为planCacheShapeHash的新字段中。If you're using an earlier MongoDB version, you'll only see the queryHash field. 如果你使用的是早期的MongoDB版本,你只会看到queryHash字段。Future MongoDB versions will remove the deprecated queryHash field, and you'll need to use the planCacheShapeHash field instead.未来的MongoDB版本将删除弃用的queryHash字段,您将需要使用planCacheShapeHash字段。

See also planCacheKey and planCacheShapeHash.另请参见planCacheKeyplanCacheShapeHash

Node.js

To use the MongoDB Node.js driver to add a $planCacheStats stage to an aggregation pipeline, use the $planCacheStats operator in a pipeline object.要使用MongoDB Node.js驱动程序将$planCacheStats阶段添加到聚合管道中,请在管道对象中使用$planCacheStatis运算符。

Return Information for All Entries in the Query Cache返回查询缓存中所有条目的信息

The following example creates a pipeline stage that returns information about the plan cache entries for the collection. The example then runs the aggregation pipeline:以下示例创建了一个管道阶段,该阶段返回有关集合的计划缓存条目的信息。然后,该示例运行聚合管道:

const pipeline = [{ $planCacheStats: {} }];

const cursor = collection.aggregate(pipeline);
return cursor;

Find Cache Entry Details for a Query Hash查找查询哈希的缓存条目详细信息

To return plan cache information for a particular query hash, include a $match stage that checks for a specific query hash in the planCacheKey field.要返回特定查询哈希的计划缓存信息,请在planCacheKey字段中包含一个$match阶段,用于检查特定查询哈希。

The following example creates a pipeline that returns information for a query hash value of "B1435201". The example then runs the aggregation pipeline:以下示例创建了一个管道,该管道返回查询哈希值"B1435201"的信息。然后,该示例运行聚合管道:

const pipeline = [
$planCacheStats: {} },
{ $match: { planCacheKey: "B1435201"} }
];

const cursor = collection.aggregate(pipeline);
return cursor;