Database Manual / Reference / Query Language / Aggregation Stages

$queryStats (aggregation stage)(聚合阶段)

Definition定义

$queryStats

Warning

The $queryStats aggregation stage is unsupported and is not guaranteed to be stable in a future release. Don't build functionality that relies on a specific output format of this stage, since the output may change in a future release.$queryStats聚合阶段不受支持,也不能保证在未来的版本中稳定。不要构建依赖于此阶段特定输出格式的功能,因为输出可能会在未来的版本中发生变化。

Returns runtime statistics for recorded queries.返回已记录查询的运行时统计信息。

$queryStats collects and reports metrics for aggregate(), find(), and distinct() queries. 集合并报告aggregate()find()distinct()查询的指标。$queryStats does not collect information for queries that use Queryable Encryption.不集合使用可查询加密的查询的信息。

Requirements需求

The $queryStats stage is enabled on deployments hosted on MongoDB Atlas with a cluster tier of at least M10.$queryStats阶段在MongoDB Atlas上托管的部署上启用,集群层至少为M10。

To run the $queryStats stage, your pipeline must meet the following requirements:要运行$queryStats阶段,您的管道必须满足以下要求:

  • The pipeline must be run on the admin database.管道必须在admin数据库上运行。
  • $queryStats must be the first stage in the pipeline.必须是管道中的第一阶段。

Syntax语法

db.adminCommand( {
aggregate: 1,
pipeline: [
{
$queryStats: {
transformIdentifiers: {
algorithm: <string>,
hmacKey: <binData> /* subtype 8 - used for sensitive data */
}
}
}
],
cursor: { }
} )

Important

You cannot run $queryStats on a specific collection. For complete examples, see Examples.您不能在特定集合上运行$queryStats。有关完整示例,请参阅示例

Command Fields命令字段

$queryStats takes the following fields:采用以下字段:

Field字段Necessity必要性Type类型Description描述
transformIdentifiersOptional可选Document文档Specifies additional transformation options for the $queryStats output.$queryStats输出指定其他转换选项。
transformIdentifiers
.algorithm
Required if specifying the transformIdentifiers object如果指定transformIdentifiers对象,则必需String字符串The type of hash transformation applied to namespace information and field names in output. The only currently supported algorithm value is hmac-sha-256.应用于输出中的命名空间信息和字段名的哈希转换类型。目前唯一支持的algorithm值是hmac-sha-256
transformIdentifiers
.hmacKey
Required if specifying the transformIdentifiers object如果指定transformIdentifiers对象,则需要binDataThe private key input in the HMAC transformation.HMAC转换中的私钥输入。

Access Control访问控制

If your deployment enforces access control, the user running $queryStats must have the following permissions:如果您的部署强制执行访问控制,则运行$queryStats的用户必须具有以下权限:

The built-in clusterMonitor role provides the queryStatsRead and queryStatsReadTransformed privileges. 内置的clusterMonitor角色提供queryStatsReadqueryStatsReadTransformed权限。The following example grants the clusterMonitor role on the admin database:以下示例授予admin数据库上的clusterMonitor角色:

db.grantRolesToUser(
"<user>",
[ { role: "clusterMonitor", db: "admin" } ]
)

Behavior行为

The following sections describe behavioral details of the $queryStats stage.以下部分描述了$queryStats阶段的行为细节。

How $queryStats Tracks Query Statistics$queryStats如何跟踪查询统计信息

Statistics for the $queryStats stage are tracked in a virtual collection that is stored in-memory. The memory limit for the virtual collection is 1% of the system's total memory.$queryStats阶段的统计信息在存储在内存中的虚拟集合中跟踪。虚拟集合的内存限制为系统总内存的1%。

How $queryStats Groups Returned Documents$queryStats如何对返回的文档进行分组

$queryStats groups queries with common properties into the same output document. The resulting document is called a query stats entry.将具有共同属性的查询分组到同一个输出文档中。生成的文档称为查询统计条目

$queryStats groups similar queries together by normalizing user-provided field values to their data types. 通过将用户提供的字段值规范化为其数据类型,将类似的查询分组在一起。For example, a filter specified as { item: 'card' } is normalized to { item : '?string'}. 例如,指定为{ item: 'card' }的筛选器被规范化为{ item : '?string'}$queryStats also normalizes the values of some query options like hint and comment.还规范了一些查询选项(如hintcomment)的值。

$queryStats preserves literal values for options like readConcern and readPreference.保留readConcernreadPreference等选项的文字值。

For the complete list of options included in a query stats entry, see find Command Query Shape.有关查询统计条目中包含的完整选项列表,请参阅查找命令查询形状

How $queryStats Transforms Data Using transformIdentifiers$queryStats如何使用转换标识符转换数据

When an HMAC key is specified to the transformIdentifiers option, $queryStats uses the HMAC key to apply an HMAC-SHA-256 hash function on the following data:当为transformIdentifiers选项指定HMAC键时,$queryStats使用HMAC键对以下数据应用HMAC-SHA-256哈希函数:

  • Document field names文档字段名称
  • Collection names集合名称
  • Database names数据库名称

$queryStats does not apply the HMAC transformation to the following data:不将HMAC转换应用于以下数据:

  • MQL keywords such as operator names (for example, $gte).MQL键,如运算符名称(例如$gte)。
  • Parameter names such as the partitionBy parameter in $setWindowFields.参数名称,如$setWindowFields中的partitionBy参数。
  • Field values. $queryStats normalizes field values in a query to their data types (such as number or string) when the query is recorded. $queryStats never stores field values that contain user data.字段值。$queryStats在记录查询时将查询中的字段值标准化为其数据类型(如数字或字符串)。$queryStats从不存储包含用户数据的字段值。

For an example of transformed output, see Transformed Example.有关转换输出的示例,请参阅转换示例

$queryStats Log Entries$queryStats日志条目

MongoDB records $queryStats operations in the deployment logs. MongoDB在部署日志中记录$queryStats操作。By default, MongoDB only logs the invocation of $queryStats operations, not the operation's output. 默认情况下,MongoDB只记录$queryStats操作的调用,而不是操作的输出。For $queryStats operations that include the transformIdentifiers option, you can specify whether the transformed output is included in the log entry.对于包含transformIdentifiers选项的$queryStats操作,您可以指定转换后的输出是否包含在日志条目中。

To learn how to control $queryStats logging behavior, see Toggle $queryStats Log Output.要了解如何控制$queryStats日志记录行为,请参阅切换$queryStat日志输出

Change Streams更改流

Query stats for change streams are updated when one of these events occur:当以下事件之一发生时,更改流的查询统计信息会更新:

  • A cursor is created游标已创建
  • A getMore operation completesgetMore操作完成
  • A cursor closes游标关闭

Query stats reported for change streams have these behaviors:为变更流报告的查询统计数据具有以下行为:

  • Execution metrics such as totalExecMicros contain information for the most recent operation (cursor creation, getMore, or cursor close).totalExecMicros等执行指标包含最近操作(游标创建、getMore或游标关闭)的信息。
  • Internal getMore operations increment the execCount metric.内部getMore操作增加execCount度量。
  • firstResponseExecMicros and totalExecMicros are always the same because stats are collected and updated for each getMore operation.firstResponseExecMicrostotalExecMicros总是相同的,因为每次getMore操作都会集合和更新统计数据。
  • When the cursor closes, lastExecutionMicros is 0.当游标关闭时,lastExecutionMicros为0。

Output输出

$queryStats returns an array of query stats entries. Some query stats entry properties contain literal values, and some properties are normalized to group common queries.返回一个查询统计条目数组。一些查询统计条目属性包含文字值,一些属性被规范化以对常见查询进行分组。

Query stats entries contain the following top-level documents:查询统计条目包含以下顶级文档:

Document文档Description描述
key

The unique combination of attributes that define an entry in the query stats output. The key contains attributes such as:在查询统计输出中定义条目的唯一属性组合。该key包含以下属性:

Each unique combination of attributes creates a separate entry in the $queryStats virtual collection.每个唯一的属性组合都会在$queryStats虚拟集合中创建一个单独的条目。

asOfThe UTC time when $queryStats read this entry from the $queryStats virtual collection. $queryStats$queryStat虚拟集合中读取此条目的UTC时间。asOf does not necessarily return the same UTC time for each result. asOf不一定为每个结果返回相同的UTC时间。Internally, the data structure is partitioned, and each partition will be read at an individual point in time.在内部,数据结构被分区,每个分区将在单独的时间点被读取。
metricsContains aggregated runtime metrics associated with each query stats entry. Each query stats entry records statistics for each query that shares the same key.包含与每个查询统计条目关联的聚合运行时指标。每个查询统计条目记录共享相同键的每个查询的统计信息。

Each document in the output array contains the following fields:输出数组中的每个文档都包含以下字段:

Field字段Type类型Literal or Normalized字面或标准化Description描述
keyDocument文档Literal字面Contains the query shape and additional query attributes that group a set of queries together包含将一组查询组合在一起的查询形状和其他查询属性
key.queryShapeDocument文档Literal字面Contains attributes used to group similar queries together. For more information, see Query Shape.包含用于将类似查询组合在一起的属性。有关详细信息,请参阅查询形状
key.clientDocument文档Literal字面Describes client information associated with the key描述与键关联的客户端信息
key.client.applicationDocument文档Literal字面The client application name客户端应用程序名称
key.client.driverDocument文档Literal字面Describes the driver used to issue the query描述用于发出查询的驱动程序
key.client.driver.nameString字符串Literal字面Name of the driver used to issue the query. Possible values include mongosh and nodejs.用于发出查询的驱动程序的名称。可能的值包括mongoshnodejs
key.client.driver.versionString字符串Literal字面Version number of the driver used to issue the query用于发出查询的驱动程序的版本号
key.client.osDocument文档Literal字面Describes the operating system used by the client that issued the query描述发出查询的客户端使用的操作系统
key.client.os.typeString字符串Literal字面Type of the operating system操作系统的类型
key.client.os.nameString字符串Literal字面Name of the operating system操作系统的名称
key.client.os.architectureString字符串Literal字面Architecture of the operating system. Possible values include arm64 and x86_64.操作系统的架构。可能的值包括arm64x86_64
key.client.os.versionString字符串Literal字面Version number of the operating system操作系统的版本号
key.readConcernDocument文档Literal字面The read concern for the key键的读取关注
key.collectionTypeString字符串Literal字面The type of collection the query was issued on. For more information, see Collection Type.发出查询的集合类型。有关详细信息,请参阅集合类型
key.hintDocument or String文档或字符串Normalized标准化The index that was used as a hint for the query用作查询提示的索引
key.batchSizeString字符串Normalized标准化The batch size for the key. Batch size specifies the maximum number of documents that can be returned in each batch of a query result. 键的批大小。批大小指定查询结果的每批中可以返回的最大文档数。By default, the initial batch size is the lesser of 101 documents or 16 mebibytes (MiB) worth of documents. 默认情况下,初始批大小为101个文档或价值16兆字节(MiB)的文档中的较小者。Subsequent batches have a maximum size of 16 MiB. batchSize can enforce a smaller limit than 16 MiB, but not a larger one. 后续批次的最大容量为16 MiB。batchSize可以强制执行小于16 MiB的限制,但不能强制执行更大的限制。When set, the batchSize is the lesser of batchSize documents or 16 MiB worth of documents.设置后,batchSizebatchSize文档或价值16 MiB的文档中的较小值。
key.commentString字符串Normalized标准化Comment associated with the key与键关联的评论
key.maxTimeMSString字符串Normalized标准化maxTimeMS value associated with the key与键关联的值
key.noCursorTimeoutBoolean布尔值Normalized标准化noCursorTimeout option associated with the key与键关联的noCursorTimeout选项
key.readPreferenceString字符串Literal字面Read preference associated with the key与键关联的读取首选项
key.apiVersionString字符串Literal字面The Stable API version associated with the key. See Stable API.与键关联的稳定API版本。参见稳定API
key.apiStrictBoolean布尔值Literal字面The apiStrict parameter value associated with the key. See Stable API Parameters.与键关联的apiStrict参数值。请参阅稳定API参数
key.apiDeprecationErrorsBoolean布尔值Literal字面The apiDeprecationErrors parameter value associated with the key. See Stable API Parameters.与键关联的apiDeprecationErrors参数值。请参阅稳定API参数
keyHashString字符串Literal字面A hashed representation of the values in the key. Each unique keyHash value corresponds to a unique entry in the $queryStats memory store.key中值的哈希表示。每个唯一的keyHash值对应于$queryStats内存存储中的一个唯一条目。
queryShapeHashString字符串Literal字面

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

queryShapeHash is a hexadecimal string with the hash of a query shape. For details, see Query Shapes.queryShapeHash是一个十六进制字符串,具有查询形状的哈希值。有关详细信息,请参阅查询形状

metricsDocument文档Literal字面Describes runtime statistics for the key描述键的运行时统计信息
metrics.lastExecutionMicrosNumberLongLiteral字面Execution runtime for the most recent query for all queries with the given key使用给定键的所有查询的最新查询的执行运行时
metrics.execCountNumberLongLiteral字面Number of times that queries with the given key have been executed执行具有给定键的查询的次数
metrics.keysExaminedDocument文档Literal字面Describes the number of keys examined by queries描述查询检查的键的数量
metrics
.keysExamined
.sum
Integer整数Literal字面Total number of keys examined检查的键总数
metrics
.keysExamined
.max
NumberLongLiteral字面Maximum number of keys examined检查键的最大数量
metrics
.keysExamined
.min
NumberLongLiteral字面Fewest number of keys examined检查的键数量最少
metrics
.keysExamined
.sumOfSquares
NumberDecimalLiteral字面

Sum of squares of number of keys examined.检查的键数量的平方和。

A high sumOfSquares value indicates high variance in the number of keys examined in individual queries.sumOfSquares值较高表示在单个查询中检查的键数差异较大。

metrics.docsExaminedDocument文档Literal字面Describes the number of documents examined by queries描述查询检查的文档数量
metrics
.docsExamined
.sum
Integer整数Literal字面Total number of documents examined in the query查询中检查的文档总数
metrics
.docsExamined
.max
NumberLongLiteral字面Maximum number of documents examined检查的最大文件数
metrics
.docsExamined
.min
NumberLongLiteral字面Minimum number of documents examined检查文件的最小数量
metrics
.docsExamined
.sumOfSquares
NumberDecimalLiteral字面

Sum of squares of number of documents examined.检查的文件数量的平方和。

A high sumOfSquares value indicates high variance in the number of documents examined in individual queries.sumOfSquares值较高表示在单个查询中检查的文档数量差异较大。

metrics.hasSortStageDocument文档Literal字面

Object that contains two fields: true and false. 包含两个字段的对象:truefalseEach field counts the number of matching queries where the value of hasSortStage is true or false, respectively.每个字段分别统计hasSortStage的值为truefalse的匹配查询的数量。

hasSortStage is true when MongoDB must sort the documents after it receives the documents from a cursor.当MongoDB从游标接收文档后必须对文档进行排序时,hasSortStagetrue

metrics.usedDiskDocument文档Literal字面

Object that contains two fields: true and false. Each field counts the number of matching queries where the value of usedDisk is true or false, respectively.包含两个字段的对象:truefalse。每个字段分别统计usedDisk值为truefalse的匹配查询的数量。

usedDisk is true when the query writes data to temporary files due to memory restrictions.当查询由于内存限制而将数据写入临时文件时,usedDisktrue

metrics.fromMultiPlannerDocument文档Literal字面

Object that contains two fields: true and false. 包含两个字段的对象:truefalseEach field counts the number of matching queries where the value of fromMultiPlanner is true or false, respectively.每个字段分别统计fromMultiPlanner的值为truefalse的匹配查询的数量。

fromMultiPlanner is true when the query planner evaluates multiple plans before choosing the winning execution plan for the query.当查询计划器在为查询选择获胜的执行计划之前评估多个计划时,fromMultiPlannertrue

metrics.fromPlanCacheDocument文档Literal字面

Object that contains two fields: true and false. 包含两个字段的对象:truefalseEach field counts the number of matching queries where the value of fromPlanCache is true or false, respectively.每个字段分别统计fromPlanCache的值为truefalse的匹配查询的数量。

fromPlanCache is true when the query planner is able to use a plan from the plan cache.当查询计划器能够使用计划缓存中的计划时,fromPlanCachetrue

metrics.totalExecMicrosDocument文档Literal字面

Describes the total time spent running queries with the given key. 描述使用给定键运行查询所花费的总时间。If the query resulted in getMores, totalExecMicros includes the time spent processing the getMore requests. 如果查询结果为getMores,则totalExecMicros包括处理getMore请求所花费的时间。totalExecMicros does not include time spent waiting for the client.totalExecMicros不包括等待客户端所花费的时间。

All subfields of totalExecMicros are reported in microseconds.totalExecMicros的所有子字段都以微秒为单位报告。

metrics
.totalExecMicros
.sum
NumberLongLiteral字面Total time spent running queries with the given key使用给定键运行查询所花费的总时间
metrics
.totalExecMicros
.max
NumberLongLiteral字面Longest amount of time spent running a query with the given key使用给定键运行查询所花费的最长时间
metrics
.totalExecMicros
.min
NumberLongLiteral字面Shortest amount of time spent running a query with the given key使用给定键运行查询所花费的最短时间
metrics
.totalExecMicros
.sumOfSquares
NumberDecimalLiteral字面Sum of squares of the total execution times for all queries with the given key. A high sumOfSquares value indicates high variance in query execution times.使用给定键的所有查询的总执行时间的平方和。sumOfSquares值高表示查询执行时间差异大。
metrics
.firstResponseExecMicros
Document文档Literal字面

Describes the time spent from when a query within the key began processing to when the server returns the first batch of results描述从键内的查询开始处理到服务器返回第一批结果所花费的时间

All subfields of firstResponseExecMicros are reported in microseconds.firstResponseExecMicros的所有子字段都以微秒为单位报告。

metrics
.firstResponseExecMicros
.sum
NumberLongLiteral字面Combined amount of time spent from the beginning of query processing to when the server returns the first batch of results从查询处理开始到服务器返回第一批结果所花费的时间总和
metrics
.firstResponseExecMicros
.max
NumberLongLiteral字面Longest amount of time spent from the beginning of query processing to when the server returns the first batch of results从查询处理开始到服务器返回第一批结果所花费的最长时间
metrics
.firstResponseExecMicros
.min
NumberLongLiteral字面Shortest amount of time spent from the beginning of query processing to when the server returns the first batch of results从查询处理开始到服务器返回第一批结果所花费的最短时间
metrics
.firstResponseExecMicros
.sumOfSquares
NumberDecimalLiteral字面

Sum of squares of amounts of time spent from the beginning of query processing to when the server returns the first batch of results.从查询处理开始到服务器返回第一批结果所花费的时间的平方和。

A high sumOfSquares value indicates high variance in query processing times.sumOfSquares值高表示查询处理时间差异大。

metrics.docsReturnedDocument文档Literal字面Describes the number of documents returned by queries within the key描述键内查询返回的文档数量
metrics
.docsReturned
.sum
NumberLongLiteral字面Total number of documents returned by queries with the given key使用给定键的查询返回的文档总数
metrics
.docsReturned
.max
NumberLongLiteral字面Maximum number of documents returned by a query with the given key使用给定键的查询返回的最大文档数
metrics
.docsReturned
.min
NumberLongLiteral字面Fewest number of documents returned by a query with the given key使用给定键的查询返回的文档数量
metrics
.docsReturned
.sumOfSquares
NumberDecimalLiteral字面

Sum of squares of number of documents returned by a query within the key.键内查询返回的文档数量的平方和。

A high sumOfSquares value indicates high variance in the number of documents returned between individual queries.sumOfSquares值较高表示单个查询之间返回的文档数量差异较大。

metrics.firstSeenTimestampDateLiteral字面Time that a query with the given key was first used since the last restart自上次重新启动以来首次使用具有给定键的查询的时间
metrics.latestSeenTimestampDateLiteral字面Time that a query with the given key was most recently used最近使用具有给定键的查询的时间
metrics.workingTimeMillisNumberLongLiteral字面The operation execution time, excluding intentional pauses such as time waiting on locks and flow control.操作执行时间,不包括有意暂停,如等待锁和流控制的时间。
metrics
.delinquentAcquisitions
NumberLongLiteral字面

Number of times that query operations exceeded the expected execution ticket acquisition time.查询操作超过预期执行票证获取时间的次数。

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

metrics
.totalAcquisitionDelinquencyMillis
NumberLongLiteral字面

Total time in milliseconds that query operations exceeded the expected execution ticket acquisition time.查询操作超过预期执行票证获取时间的总时间(毫秒)。

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

metrics
.maxAcquisitionDelinquencyMillis
NumberLongLiteral字面

Longest duration of time in milliseconds that a query operation exceeded the expected execution ticket acquisition time.查询操作超过预期执行票证获取时间的最长持续时间(毫秒)。

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

metrics
.cpuNanos
Document文档Literal字面

Contains metrics related to CPU usage for a query operation. This document is only available on Linux systems.包含与查询操作的CPU使用率相关的指标。本文档仅在Linux系统上可用。

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

metrics
.cpuNanos
.sum
NumberLongLiteral字面

The total CPU time spent by a query operation in nanoseconds. This field is only available on Linux systems.查询操作所花费的总CPU时间(以纳秒为单位)。此字段仅在Linux系统上可用。

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

metrics
.cpuNanos
.max
NumberLongLiteral字面

The maximum CPU time spent on a query operation in nanoseconds. This field is only available on Linux systems.查询操作所花费的最大CPU时间(以纳秒为单位)。此字段仅在Linux系统上可用。

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

metrics
.cpuNanos
.min
NumberLongLiteral字面

The minimum CPU time spent on a query operation in nanoseconds. This field is only available on Linux systems.查询操作所花费的最小CPU时间(以纳秒为单位)。此字段仅在Linux系统上可用。

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

metrics
.cpuNanos
.sumOfSquares
NumberDecimalLiteral字面

Sum of squares of CPU time spent on query operations. This field is only available on Linux systems.查询操作所花费的CPU时间的平方和。此字段仅在Linux系统上可用。

A high sumOfSquares value indicates high variance in the CPU time for individual queries.sumOfSquares值高表示单个查询的CPU时间差异大。

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

Collection Type集合类型

The key.collectionType field indicates the type of collection that the recorded query was issued on. The collectionType can be one of the following values:key.collectionType字段指示发出记录查询的集合类型。collectionType可以是以下值之一:

Field字段Description描述
changeStreamThe query was a change stream operation.查询是一个更改流操作
collectionThe query was issued on a standard collection.查询是在标准集合上发出的。
nonExistentThe query was issued on a collection that does not exist.查询是在不存在的集合上发出的。
timeseriesThe query was issued on a timeseries collection.查询是针对时间序列集合发出的。
viewThe query was issued on a view.查询是针对某个视图发出的。
virtual

The query was issued on a virtual collection. The following operations occur in virtual collections:查询是在虚拟集合上发出的。以下操作发生在虚拟集合中:

Query Shape查询形状

The key.queryShape document contains query shape fields. To learn about query shapes, see Query Shapes.key.queryShape文档包含查询形状字段。要了解查询形状,请参阅查询形状

The fields in key.queryShape vary based on the command that resulted in the query stats entry. $queryStats creates query stats entries for aggregate, find, distinct, and count commands.key.queryShape中的字段会根据导致查询统计条目的命令而变化。$queryStatsaggregatefinddistinctcount命令创建查询统计条目。

Each query shape property corresponds to a query option. For example, key.queryShape.sort corresponds to the sort() specification for the query shape.每个查询形状属性都对应一个查询选项。例如,key.queryShape.sort对应于查询形状的sort()规范。

find Command Query Shape查找命令查询形状

The following table describes the query shape properties for find commands.下表描述了find命令的查询形状属性。

Field字段Type类型Literal or Normalized字面或标准化
key.queryShape.filterDocument文档Normalized标准化
key.queryShape.sortDocument文档Literal字面
key.queryShape.projectionDocument文档Normalized标准化
key.queryShape.skipInteger整数Normalized标准化
key.queryShape.limitInteger整数Normalized标准化
key.queryShape.singleBatchBoolean布尔值Literal字面
key.queryShape.maxDocument文档Normalized标准化
key.queryShape.minDocument文档Normalized标准化
key.queryShape.returnKeyBoolean布尔值Literal字面
key.queryShape.showRecordIdBoolean布尔值Literal字面
key.queryShape.tailableBoolean布尔值Literal字面
key.queryShape.oplogReplayBoolean布尔值Literal字面
key.queryShape.awaitDataBoolean布尔值Literal字面
key.queryShape.collationDocument文档Literal字面
key.queryShape.allowDiskUseBoolean布尔值Literal字面
key.queryShape.letDocument文档Normalized标准化

aggregate Command Query Shape聚合命令查询形状

The following table describes the query shape properties for aggregate commands.下表描述了aggregate命令的查询形状属性。

Field字段Type类型Literal or Normalized字面或标准化
key.queryShape.pipelineArray数组Normalized标准化
key.queryShape.explainBoolean布尔值Literal字面
key.queryShape.allowDiskUseBoolean布尔值Literal字面
key.queryShape.collationDocument文档Literal字面
key.queryShape.hintString or Document字符串或文档Normalized标准化
key.queryShape.letDocument文档Normalized标准化

distinct Command Query Shape不同的命令查询形状

The following table describes the query shape properties for distinct commands.下表描述了distinct命令的查询形状属性。

Field字段Type类型Literal or Normalized字面或标准化
key.queryShape.collationDocument文档Normalized标准化
key.queryShape.keyString字符串Literal字面
key.queryShape.queryDocument文档Normalized标准化

count Command Query Shapecount命令查询形状

The following table describes the query shape properties for count commands.下表描述了count命令的查询形状属性。

Field字段Type类型Literal or Normalized字面或标准化
key.queryShape.collationDocument文档Normalized标准化
key.queryShape.queryDocument文档Normalized标准化
key.queryShape.limitInteger整数Normalized标准化
key.queryShape.skipInteger整数Normalized标准化

Supplemental Metrics补充指标

Query stats entries may contain a metrics.supplementalMetrics document that provides additional information about your queries.查询统计条目可能包含一个metrics.supplementalMetrics文档,提供有关查询的其他信息。

$vectorSearch Metrics$vectorSearch指标

If your query shape contains $vectorSearch, $queryStats outputs the following supplemental metrics:如果您的查询形状包含$vectorSearch$queryStats将输出以下补充指标:

Field字段Type类型Description描述
metrics
.supplementalMetrics
.vectorSearch
Document文档Supplemental metrics about a $vectorSearch aggregation stage关于$vectorSearch聚合阶段的补充指标
metrics
.supplementalMetrics
.vectorSearch
.limit
Document文档Metrics related to the limit value of the $vectorSearch aggregation stage$vectorSearch聚合阶段的limit值相关的度量
metrics
.supplementalMetrics
.vectorSearch
.numCandidatesLimitRatio
Document文档Metrics related to the numCandidates value of the $vectorSearch aggregation stage. $vectorSearch聚合阶段的numCandidates值相关的度量。$queryStats expresses these metrics as a ratio of numCandidates divided by the limit value.$queryStats将这些指标表示为numCandidates除以limit值的比率。

Examples示例

MongoDB Shell

To run the examples in this section, start with the following data:要运行本节中的示例,请从以下数据开始:

db.products.insertMany(
[
{ item: "card", qty: 15 },
{ item: "envelope", qty: 20 },
{ item: "stamps" , qty: 30 }
]
)

Then, run these commands:然后,运行以下命令:

db.products.find( { item: "card" } )

db.products.aggregate( [
{
$match: { qty: { $gt: 20 } }
}
] )

The following examples show the output of $queryStats using different types of data transformation:以下示例显示了使用不同类型的数据转换的$queryStats的输出:

The example $queryStats output in the following sections may vary based on the execution of other commands.以下部分中的示例$queryStats输出可能因其他命令的执行而异。

Untransformed Example未转换示例

Input:输入:

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

Output:输出:

[
{
key: {
queryShape: {
cmdNs: { db: 'test', coll: 'products' },
command: 'find',
filter: { item: { '$eq': '?string' } }
},
client: {
driver: { name: 'nodejs|mongosh', version: '5.1.0' },
os: {
type: 'Darwin',
name: 'darwin',
architecture: 'arm64',
version: '22.6.0'
},
platform: 'Node.js v16.19.1, LE (unified)',
version: '5.1.0|1.8.0',
application: { name: 'mongosh 1.8.0' }
},
collectionType: 'collection'
},
keyHash: 'dsoJ+LHAru0z6MJ1/IygJnnLTrlpVYYmPnlmNZbZrLI=',
queryShapeHash: "uxMLCvpiJ5N/IRqt4c28/0A8F01C8AA16CA805FF5C1A5737535F97E40C2A90CE91A82CCB7A74C7CCB9C48",
metrics: {
lastExecutionMicros: Long("4254"),
execCount: Long("1"),
totalExecMicros: {
sum: Long("4254"),
max: Long("4254"),
min: Long("4254"),
sumOfSquares: Decimal128("18096516")
},
firstResponseExecMicros: {
sum: Long("4254"),
max: Long("4254"),
min: Long("4254"),
sumOfSquares: Decimal128("18096516")
},
docsReturned: {
sum: Long("1"),
max: Long("1"),
min: Long("1"),
sumOfSquares: Decimal128("1")
},
firstSeenTimestamp: ISODate("2023-09-14T12:30:27.989Z"),
latestSeenTimestamp: ISODate("2023-09-14T12:30:27.989Z")
},
asOf: Timestamp({ t: 1694695007, i: 0 })
},
{
key: {
queryShape: {
cmdNs: { db: 'test', coll: 'products' },
command: 'aggregate',
pipeline: [
{ '$match': { qty: { '$gt': '?number' } } }
]
},
apiVersion: '1',
client: {
driver: { name: 'nodejs|mongosh', version: '5.1.0' },
os: {
type: 'Darwin',
name: 'darwin',
architecture: 'arm64',
version: '22.6.0'
},
platform: 'Node.js v16.19.1, LE (unified)',
version: '5.1.0|1.8.0',
application: { name: 'mongosh 1.8.0' }
},
collectionType: 'collection',
cursor: { batchSize: '?number' }
},
keyHash: '2QLBfL0m1lliStdN4XvBjqVBtZQ6ffaB2L1pJ99twT8=',
queryShapeHash: "uxMLCvpiJ5N/IRqt4c28/0A8F01C8AA16CA805FF5C1A5737535F97E40C2A90CE91A82CCB7A74C7CCB9C48",
metrics: {
lastExecutionMicros: Long("350"),
execCount: Long("3"),
totalExecMicros: {
sum: Long("3084"),
max: Long("2499"),
min: Long("235"),
sumOfSquares: Decimal128("6422726")
},
firstResponseExecMicros: {
sum: Long("3084"),
max: Long("2499"),
min: Long("235"),
sumOfSquares: Decimal128("6422726")
},
docsReturned: {
sum: Long("3"),
max: Long("1"),
min: Long("1"),
sumOfSquares: Decimal128("3")
},
firstSeenTimestamp: ISODate("2023-11-29T21:16:17.796Z"),
latestSeenTimestamp: ISODate("2023-11-29T21:17:12.385Z")
},
asOf: Timestamp({ t: 1701292827, i: 0 })
}
]

Transformed Example转换示例

Input:输入:

db.getSiblingDB("admin").aggregate( [
{
$queryStats: {
transformIdentifiers: {
algorithm: "hmac-sha-256" ,
hmacKey: BinData(8, "87c4082f169d3fef0eef34dc8e23458cbb457c3sf3n2")
}
}
}
] )

Output:输出:

[
{
key: {
queryShape: {
cmdNs: {
db: 'Mtrt3iG7dsX5c5uCSIhSVlcu5qD3u3xx2EQnS1dJLxM=',
coll: '3oJE6AyOuf8h5NqWiXETxulFlPm3QUXbMnMjL2EqAU4='
},
command: 'find',
filter: {
'VWVRow7Ure92ajRPfrpWiU8OtDeWcLePFIq0+tooBng=': { '$eq': '?string' }
}
},
client: {
driver: { name: 'nodejs|mongosh', version: '5.1.0' },
os: {
type: 'Darwin',
name: 'darwin',
architecture: 'arm64',
version: '22.6.0'
},
platform: 'Node.js v16.19.1, LE (unified)',
version: '5.1.0|1.8.0',
application: { name: 'mongosh 1.8.0' }
},
collectionType: 'collection'
},
keyHash: 'q4vxam+wbk8tTrl8D0MDFH1LQAbI8fWspfkGKhEUROk=',
queryShapeHash: "uxMLCvpiJ5N/IRqt4c28/0A8F01C8AA16CA805FF5C1A5737535F97E40C2A90CE91A82CCB7A74C7CCB9C48",
metrics: {
lastExecutionMicros: Long("4254"),
execCount: Long("1"),
keysExamined: {
sum: Int("5"),
max: Long("5"),
min: Long("5"),
sumOfSquares: Decimal128("25")
},
docsExamined: {
sum: Long("1"),
max: Long("1"),
min: Long("1"),
sumOfSquares: Decimal128("1")
},
hasSortStage: {true: Long("0"), false: Long("1")},
usedDisk: {true: Long("0"), false: Long("1")},
fromMultiPlanner: {true: Long("0"), false: Long("1")},
fromPlanCache: {true: Long("1"), false: Long("0")},
totalExecMicros: {
sum: Long("4254"),
max: Long("4254"),
min: Long("4254"),
sumOfSquares: Decimal128("18096516")
},
firstResponseExecMicros: {
sum: Long("4254"),
max: Long("4254"),
min: Long("4254"),
sumOfSquares: Decimal128("18096516")
},
docsReturned: {
sum: Long("1"),
max: Long("1"),
min: Long("1"),
sumOfSquares: Decimal128("1")
},
firstSeenTimestamp: ISODate("2023-09-14T12:30:27.989Z"),
latestSeenTimestamp: ISODate("2023-09-14T12:30:27.989Z")
},
asOf: Timestamp({ t: 1694695712, i: 0 })
},
{
key: {
queryShape: {
cmdNs: {
db: 'Mtrt3iG7dsX5c5uCSIhSVlcu5qD3u3xx2EQnS1dJLxM=',
coll: '3oJE6AyOuf8h5NqWiXETxulFlPm3QUXbMnMjL2EqAU4='
},
command: 'aggregate',
pipeline: [
{
'$match': {
'RVqrwNEPotzdKnma/T7s4YcgNvpqO29BMDoni2N4IMI=': { '$gt': '?number' }
}
}
]
},
apiVersion: '1',
client: {
driver: { name: 'nodejs|mongosh', version: '5.1.0' },
os: {
type: 'Darwin',
name: 'darwin',
architecture: 'arm64',
version: '22.6.0'
},
platform: 'Node.js v16.19.1, LE (unified)',
version: '5.1.0|1.8.0',
application: { name: 'mongosh 1.8.0' }
},
collectionType: 'collection',
cursor: { batchSize: '?number' }
},
keyHash: 'HEhpQTYB+/wVoHLkOkMd+EC2jguQlMJ1N/vTE7+b8Js=',
queryShapeHash: "uxMLCvpiJ5N/IRqt4c28/0A8F01C8AA16CA805FF5C1A5737535F97E40C2A90CE91A82CCB7A74C7CCB9C48",
metrics: {
lastExecutionMicros: Long("350"),
execCount: Long("3"),
keysExamined: {
sum: Int("5"),
max: Long("5"),
min: Long("5"),
sumOfSquares: Decimal128("25")
},
docsExamined: {
sum: Long("1"),
max: Long("1"),
min: Long("1"),
sumOfSquares: Decimal128("1")
},
hasSortStage: {true: Long("0"), false: Long("1")},
usedDisk: {true: Long("0"), false: Long("1")},
fromMultiPlanner: {true: Long("0"), false: Long("1")},
fromPlanCache: {true: Long("1"), false: Long("0")},
totalExecMicros: {
sum: Long("3084"),
max: Long("2499"),
min: Long("235"),
sumOfSquares: Decimal128("6422726")
},
firstResponseExecMicros: {
sum: Long("3084"),
max: Long("2499"),
min: Long("235"),
sumOfSquares: Decimal128("6422726")
},
docsReturned: {
sum: Long("3"),
max: Long("1"),
min: Long("1"),
sumOfSquares: Decimal128("3")
},
firstSeenTimestamp: ISODate("2023-11-29T21:16:17.796Z"),
latestSeenTimestamp: ISODate("2023-11-29T21:17:12.385Z")
},
asOf: Timestamp({ t: 1701293302, i: 0 })
},
]
Node.js

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

Untransformed Example未转换示例

The following example creates a pipeline stage that outputs untransformed runtime statistics about recorded queries. The example then runs the aggregation pipeline:以下示例创建了一个管道阶段,该阶段输出有关已记录查询的未转换运行时统计信息。然后,该示例运行聚合管道:

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

const adminDb = client.db("admin");
const cursor = adminDb.aggregate(pipeline);
return cursor;

Transformed Example转换示例

To return transformed query statistics, include the transformIdentifiers field in the pipeline stage:要返回转换后的查询统计信息,请在管道阶段中包含transformIdentifiers字段:

const pipeline = [
{
$queryStats: {
transformIdentifiers: {
algorithm: "hmac-sha-256",
hmacKey: new Binary(Buffer.from("87c4082f169d3fef0eef34dc8e23458cbb457c3aabbccddeeff00112233445566778899", "hex"), 8)
}
}
}
];

const adminDb = client.db("admin");
const cursor = adminDb.aggregate(pipeline);
return cursor;

MongoDB Atlas Data CollectionMongoDB Atlas数据集合

MongoDB Atlas periodically uses $queryStats to collect anonymized data about your queries, which helps improve MongoDB products. Your data may also be used to make feature suggestions based on usage. MongoDB retains the data it collects with $queryStats for four years.MongoDB Atlas会定期使用$queryStats集合有关查询的匿名数据,这有助于改进MongoDB产品。您的数据也可能用于根据使用情况提出功能建议。MongoDB将使用$queryStats集合的数据保留四年。

When Atlas runs $queryStats on your deployment, it uses a unique HMAC key per Atlas organization to transform your data and avoid collecting sensitive information.当Atlas在您的部署上运行$queryStats时,它会为每个Atlas组织使用一个唯一的HMAC键来转换您的数据并避免集合敏感信息。