$planCacheStats

On this page本页内容

Definition定义

$planCacheStats

New in version 4.2.在版本4.2中新增

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. $planCacheStats阶段必须是管道中的第一个阶段。The stage takes an empty document as a parameter and has the following syntax:阶段取用一个空文档作为参数,语法如下:

{ $planCacheStats: { } }
Note注意
4.4 Changes4.4变更

Starting in version 4.4,从版本4.4开始,

Tip提示
See also: 参阅:

Considerations注意事项

Pipeline管道

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

Restrictions限制

Access Control访问控制

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

Read Preference读取首选项

$planCacheStats observes the read preference in selecting the host(s) from which to return the plan cache information.在选择要从中返回计划缓存信息的主机时观察读取首选项

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输出

For each plan cache entry, the $planCacheStats stage returns a document similar to the following:对于每个计划缓存条目,$planCacheStats阶段将返回一个类似于以下内容的文档:

{
   "createdFromQuery" : <document>,
   "queryHash" : <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>, // Available starting in MongoDB 5.0, 4.4.3, 4.2.12, 4.0.23, 3.6.23
   "host" : <string>,   // Available starting in MongoDB 4.4
   "shard" : <string>   // Available starting in MongoDB 4.4 if run on sharded cluster
}

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

Field字段Description描述
createdFromQuery

A document that contains the specific query that resulted in this cache entry; i.e.包含导致该缓存条目的特定查询的文档;即。

{
  "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.如果处于非活动状态,则查询计划器当前未使用该条目生成查询计划。
Tip提示
queryHash

A hexadecimal string that represents the hash of the query shape. 表示查询形状哈希的十六进制字符串。For more information, see 有关更多信息,请参阅explain.queryPlanner.queryHash

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 query shape and the currently available indexes for that shape. 计划缓存键是查询形状和该形状的当前可用索引的函数。For more information, see 有关更多信息,请参阅explain.queryPlanner.planCacheKey

cachedPlan

The details of the cached plan. 缓存计划的详细信息。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
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 the an index filter exists for the query shape.指示查询形状是否存在索引筛选器的布尔值。
estimatedSizeBytes

A number that describes the estimated size in bytes of a plan cache entry.描述计划缓存项的估计大小(以字节为单位)的数字。

New in version 5.0.在版本5.0中新增 (Also available starting in 4.4.3, 4.2.12, 4.0.23, and 3.6.23也可从4.4.3、4.2.12、4.0.23和3.6.23开始)

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. 该成员由shardhost字段标识。See also Read Preference.另请参阅读取首选项

New in version 4.4.在版本4.4中新增

shard

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

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

New in version 4.4.在版本4.4中新增

Examples示例

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

db.orders.insertMany( [
   { "_id" : 1, "item" : "abc", "price" : NumberDecimal("12"), "quantity" : 2, "type": "apparel" },
   { "_id" : 2, "item" : "jkl", "price" : NumberDecimal("20"), "quantity" : 1, "type": "electronics" },
   { "_id" : 3, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : 5, "type": "apparel" },
   { "_id" : 4, "item" : "abc", "price" : NumberDecimal("8"), "quantity" : 10, "type": "apparel" },
   { "_id" : 5, "item" : "jkl", "price" : NumberDecimal("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: NumberDecimal("10")} } }
);
Note注意

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

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

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

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

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

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

The operation returns all entries in the cache:该操作返回缓存中的所有条目:

{
                                               // Plan Cache Entry 1
   "createdFromQuery" : {
      "query" : { "quantity" : { "$gte" : 5 }, "type" : "apparel" },
      "sort" : { },
      "projection" : { }
   },
   "queryHash" : "4D151C4C",
   "planCacheKey" : "DD67E353",
   "isActive" : false,
   "works" : NumberLong(4),
   "cachedPlan" : {
      ...
   },
   "timeOfCreation" : ISODate("2020-02-06T18:15:44.849Z"),
   "creationExecStats" : [
      {
         ... // Exec Stats for Candidate 1
      },
      {
         ... // Exec Stats for Candidate 2
      }
   ],
   "candidatePlanScores" : [
      1.5002,
      1.5002
   ],
   "indexFilterSet" : false,
   "estimatedSizeBytes" : NumberLong(3160),
     // Available starting in MongoDB 5.0, 4.4.3, 4.2.12, 4.0.23, 3.6.23
   "host" : "mongodb1.example.net:27018",
       // Available starting in MongoDB 4.4
   "shard" : "shardA"
                           // Available starting in MongoDB 4.4 if run on sharded cluster
}
{
                                               // Plan Cache Entry 2
   "createdFromQuery" : {
      "query" : { "quantity" : { "$gte" : 20 } },
      "sort" : { },
      "projection" : { }
   },
   "queryHash" : "23B19B75",
   "planCacheKey" : "6F23F858",
   "isActive" : false,
   "works" : NumberLong(1),
   "cachedPlan" : {
      ...
   },
   "timeOfCreation" : ISODate("2020-02-06T18:15:44.454Z"),
   "creationExecStats" : [
      {
         ... // Exec Stats for Candidate 1
      },
      {
         ... // Exec Stats for Candidate 2
      }
   ],
   "candidatePlanScores" : [
      1.0002,
      1.0002
   ],
   "indexFilterSet" : false,
   "estimatedSizeBytes" : NumberLong(2539),
     // Available starting in MongoDB 5.0, 4.4.3, 4.2.12, 4.0.23, 3.6.23
   "host" : "mongodb1.example.net:27018",
       // Available starting in MongoDB 4.4
   "shard" : "shardA"
                           // Available starting in MongoDB 4.4 if run on sharded cluster
}
{
                                               // Plan Cache Entry 3
   "createdFromQuery" : {
      "query" : { "item" : "abc", "price" : { "$gte" : NumberDecimal("5") } },
      "sort" : { },
      "projection" : { }
   },
   "queryHash" : "117A6B10",
   "planCacheKey" : "A1824628",
   "isActive" : true,
   "works" : NumberLong(4),
   "cachedPlan" : {
      ...
   },
   "timeOfCreation" : ISODate("2020-02-06T18:15:44.452Z"),
   "creationExecStats" : [
      {
         ... // Exec Stats for Candidate 1
      },
      {
         ... // Exec Stats for Candidate 2
      }
   ],
   "candidatePlanScores" : [
      1.7502,
      1.7502
   ],
   "indexFilterSet" : false,
   "estimatedSizeBytes" : NumberLong(3183),
     // Available starting in MongoDB 5.0, 4.4.3, 4.2.12, 4.0.23, 3.6.23
   "host" : "mongodb1.example.net:27018",
       // Available starting in MongoDB 4.4
   "shard" : "shardA"
                           // Available starting in MongoDB 4.4 if run on sharded cluster
}
{
                                               // Plan Cache Entry 4
   "createdFromQuery" : {
      "query" : { "item" : "abc", "price" : { "$gte" : NumberDecimal("10") } },
      "sort" : { },
      "projection" : { }
   },
   "queryHash" : "117A6B10",
   "planCacheKey" : "2E6E536B",
   "isActive" : true,
   "works" : NumberLong(3),
   "cachedPlan" : {
      ...
   },
   "timeOfCreation" : ISODate("2020-02-06T18:15:44.449Z"),
   "creationExecStats" : [
      {
         ... // Exec Stats for Candidate 1
      },
      {
         ... // Exec Stats for Candidate 2
      },
      {
         ... // Exec Stats for Candidate 3
      }
   ],
   "candidatePlanScores" : [
      1.6668666666666665,
      1.6668666666666665,
      1.6668666666666665
   ],
   "indexFilterSet" : false,
   "estimatedSizeBytes" : NumberLong(4653),
     // Available starting in MongoDB 5.0, 4.4.3, 4.2.12, 4.0.23, 3.6.23
   "host" : "mongodb1.example.net:27018",
       // Available starting in MongoDB 4.4
   "shard" : "shardA"
                           // Available starting in MongoDB 4.4 if run on sharded cluster
}

See also planCacheKey.另请参见planCacheKey

List Query Shapes列表查询形状

MongoDB 4.4 removes the deprecated planCacheListQueryShapes command and its helper method PlanCache.listQueryShapes().MongoDB 4.4删除了不推荐使用的planCacheListQueryShapes命令及其助手方法PlanCache.listQueryShapes()

As an alternative, you can use the $planCacheStats stage to obtain a list of all of the query shapes for which there is a cached plan.或者,您可以使用$planCacheStats阶段来获取存在缓存计划的所有查询形状的列表。

For example, the following uses the $project stage to only output the createdFromQuery field and the queryHash field.例如,下面使用$project阶段仅输出createdFromQuery字段和queryHash字段。

db.orders.aggregate( [ { $planCacheStats: { } } , { $project: {createdFromQuery: 1, queryHash: 1 } } ] )

The operation returns the following query shapes:该操作返回以下查询形状:

{ "createdFromQuery" : { "query" : { "item" : "abc", "price" : { "$gte" : NumberDecimal("5") } }, "sort" : {  }, "projection" : {  } }, "queryHash" : "117A6B10" }
{ "createdFromQuery" : { "query" : { "quantity" : { "$gte" : 5 }, "type" : "apparel" }, "sort" : {  }, "projection" : {  } }, "queryHash" : "4D151C4C" }
{ "createdFromQuery" : { "query" : { "quantity" : { "$gte" : 20 } }, "sort" : {  }, "projection" : {  } }, "queryHash" : "23B19B75" }
{ "createdFromQuery" : { "query" : { "item" : "abc", "price" : { "$gte" : NumberDecimal("10") } }, "sort" : {  }, "projection" : {  } }, "queryHash" : "117A6B10" }

Find Cache Entry Details for a Query Shape查找查询形状的缓存项详细信息

To return plan cache information for a particular query shape, 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 and $project to return specific information for a particular query shape:以下聚合管道使用$planCacheStats后跟$match$project来返回特定查询形状的特定信息:

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

The operation returns the following:运算结果如下:

{
   "createdFromQuery" : {
      "query" : { "quantity" : { "$gte" : 5 }, "type" : "apparel" },
      "sort" : { },
      "projection" : { }
   },
   "queryHash" : "4D151C4C",
   "planCacheKey" : "DD67E353",
   "isActive" : false,
   "works" : NumberLong(4),
   "cachedPlan" : {
      "stage" : "FETCH",
      "filter" : {
         "type" : {
            "$eq" : "apparel"
         }
      },
      "inputStage" : {
         "stage" : "IXSCAN",
         "keyPattern" : {
            "quantity" : 1
         },
         "indexName" : "quantity_1",
         "isMultiKey" : false,
         "multiKeyPaths" : {
            "quantity" : [ ]
         },
         "isUnique" : false,
         "isSparse" : false,
         "isPartial" : false,
         "indexVersion" : 2,
         "direction" : "forward",
         "indexBounds" : {
            "quantity" : [
               "[5.0, inf.0]"
            ]
         }
      }
   },
   "timeOfCreation" : ISODate("2020-02-06T18:15:44.849Z"),
   "creationExecStats" : [
      {
         "nReturned" : 2,
         "executionTimeMillisEstimate" : 0,
         "totalKeysExamined" : 3,
         "totalDocsExamined" : 3,
         "executionStages" : {
            "stage" : "FETCH",
            "filter" : {
               "type" : {
                  "$eq" : "apparel"
               }
            },
            "nReturned" : 2,
            "executionTimeMillisEstimate" : 0,
            "works" : 4,
            "advanced" : 2,
            "needTime" : 1,
            "needYield" : 0,
            "saveState" : 0,
            "restoreState" : 0,
            "isEOF" : 1,
            "docsExamined" : 3,
            "alreadyHasObj" : 0,
            "inputStage" : {
               "stage" : "IXSCAN",
               "nReturned" : 3,
               "executionTimeMillisEstimate" : 0,
               "works" : 4,
               "advanced" : 3,
               "needTime" : 0,
               "needYield" : 0,
               "saveState" : 0,
               "restoreState" : 0,
               "isEOF" : 1,
               "keyPattern" : {
                  "quantity" : 1
               },
               "indexName" : "quantity_1",
               "isMultiKey" : false,
               "multiKeyPaths" : {
                  "quantity" : [ ]
               },
               "isUnique" : false,
               "isSparse" : false,
               "isPartial" : false,
               "indexVersion" : 2,
               "direction" : "forward",
               "indexBounds" : {
                  "quantity" : [
                     "[5.0, inf.0]"
                  ]
               },
               "keysExamined" : 3,
               "seeks" : 1,
               "dupsTested" : 0,
               "dupsDropped" : 0
            }
         }
      },
      {
         "nReturned" : 2,
         "executionTimeMillisEstimate" : 0,
         "totalKeysExamined" : 3,
         "totalDocsExamined" : 2,
         "executionStages" : {
            "stage" : "FETCH",
            "nReturned" : 2,
            "executionTimeMillisEstimate" : 0,
            "works" : 4,
            "advanced" : 2,
            "needTime" : 1,
            "needYield" : 0,
            "saveState" : 0,
            "restoreState" : 0,
            "isEOF" : 1,
            "docsExamined" : 2,
            "alreadyHasObj" : 0,
            "inputStage" : {
               "stage" : "IXSCAN",
               "nReturned" : 2,
               "executionTimeMillisEstimate" : 0,
               "works" : 4,
               "advanced" : 2,
               "needTime" : 1,
               "needYield" : 0,
               "saveState" : 0,
               "restoreState" : 0,
               "isEOF" : 1,
               "keyPattern" : {
                  "quantity" : 1,
                  "type" : 1
               },
               "indexName" : "quantity_1_type_1",
               "isMultiKey" : false,
               "multiKeyPaths" : {
                  "quantity" : [ ],
                  "type" : [ ]
               },
               "isUnique" : false,
               "isSparse" : false,
               "isPartial" : false,
               "indexVersion" : 2,
               "direction" : "forward",
               "indexBounds" : {
                  "quantity" : [
                     "[5.0, inf.0]"
                  ],
                  "type" : [
                     "[\"apparel\", \"apparel\"]"
                  ]
               },
               "keysExamined" : 3,
               "seeks" : 2,
               "dupsTested" : 0,
               "dupsDropped" : 0
            }
         }
      }
   ],
   "candidatePlanScores" : [
      1.5002,
      1.5002
   ],
   "indexFilterSet" : false,
   "estimatedSizeBytes" : NumberLong(3160),
     // Available starting in MongoDB 5.0, 4.4.3, 4.2.12, 4.0.23, 3.6.23
   "host" : "mongodb1.example.net:27018",
       // Available starting in MongoDB 4.4
   "shard" : "shardA"
                           // Available starting in MongoDB 4.4 if run on sharded cluster
}

See also planCacheKey and queryHash.另请参见planCacheKeyqueryHash

←  $out (aggregation)$project (aggregation) →