定义
$indexStats返回集合中每个索引使用情况的统计信息。如果在运行时存在访问控制,请至少以具有
clusterMonitor角色的用户身份进行验证。The
$indexStatsstage takes an empty document and has the following syntax:{ $indexStats: { } } 对于每个索引,返回文档包含以下字段:
输出字段说明name索引名称。
索引密钥规范。
另请参阅:规范。
mongod进程的主机名和端口。Index usage metrics for the associated host, including:
ops:使用索引的操作次数。这不包括内部操作,例如通过 TTL 索引进行的删除或数据块分割和迁移操作。since:MongoDB 收集统计数据的时间
WARNING: The
accessesfield reports index usage metrics only for the node where the query runs. For more comprehensive index usage statistics, run$indexStatson each node in the cluster.与主机关联的分片的名称
仅适用于分片群集。
索引的完整规范文档,其中包括索引键和索引属性。
仅当值为
true时才包含索引选项hidden。指示索引当前是否正在构建。
仅当
true时才可用。
行为
Accesses 字段
The statistics reported by the accesses field only apply to the node where the query is being run and only include index access driven by user requests. It does not include internal operations like deletion via TTL indexes or chunk split and migration operations.
限制
$indexStats必须是聚合管道的第一阶段。$indexStats不允许在事务中使用。
索引统计数据重置注意事项
示例
例如,集合 orders 包含以下文档:
db.orders.insertMany( [ { _id : 1, item : "abc", price : 12, quantity : 2, type: "apparel" }, { _id : 2, item : "jkl", price : 20, quantity : 1, type: "electronics" }, { _id : 3, item : "abc", price : 10, quantity : 5, type: "apparel" } ] )
在集合上创建以下两个索引:
db.orders.createIndex( { item: 1, quantity: 1 } ) db.orders.createIndex( { type: 1, item: 1 } ) db.orders.createIndex( { price: 1 }, { partialFilterExpression: { type: "apparel" } } )
对集合运行一些查询:
db.orders.find( { type: "apparel"} ) db.orders.find( { item: "abc" } ).sort( { quantity: 1 } ) db.orders.find( { price: { $gt: 10 } } )
如需查看 orders 集合中索引使用情况的统计信息,请运行以下聚合操作:
db.orders.aggregate( [ { $indexStats: { } } ] )
该操作将返回一个包含每个索引的使用统计信息的文档:
[ { name: 'type_1_item_1', key: { type: 1, item: 1 }, host: 'examplehost.local:27018', accesses: { ops: Long("1"), since: ISODate("2024-05-02T15:07:21.420Z") }, shard: "shardA", spec: { v: 2, key: { type: 1, item: 1 }, name: 'type_1_item_1' } }, { name: 'item_1_quantity_1', key: { item: 1, quantity: 1 }, host: 'examplehost.local:27018', accesses: { ops: Long("1"), since: ISODate("2024-05-02T15:07:21.254Z") }, shard: "shardA", spec: { v: 2, key: { item: 1, quantity: 1 }, name: 'item_1_quantity_1' } }, { name: '_id_', key: { _id: 1 }, host: 'examplehost.local:27018', accesses: { ops: Long("0"), since: ISODate("2024-05-02T15:07:13.274Z") }, shard: "shardA", spec: { v: 2, key: { _id: 1 }, name: '_id_' } }, { name: 'price_1', key: { price: 1 }, host: 'examplehost.local:27018', accesses: { ops: Long("0"), since: ISODate("2024-05-02T15:07:54.847Z") }, shard: "shardA", spec: { v: 2, key: { price: 1 }, name: 'price_1', partialFilterExpression: { type: 'apparel' } } } ]
要使用MongoDB Node.js驱动程序将 $indexStats 阶段添加到聚合管道,请在管道对象中使用 $indexStats操作符。
以下示例创建了一个管道阶段,该阶段返回一个文档,其中包含集合上每个索引的使用情况统计信息。然后,该示例运行聚合管道:
const pipeline = [{ $indexStats: {} }]; const cursor = collection.aggregate(pipeline); return cursor;