Docs 主页 → 开发应用程序 → MongoDB Manual
$indexStats(聚合)
定义
$indexStats
返回集合中每个索引使用情况的统计信息。如果在运行时存在访问控制,请至少以具有
clusterMonitor
角色的用户身份进行验证。$indexStats
阶段接受空文档并具有以下事务语法:{ $indexStats: { } } 对于每个索引,返回文档包含以下字段:
索引的统计数据将在
mongod
重启或索引删除和重新创建时重置。
行为
Accesses 字段
accesses字段报告的统计信息仅包括由用户请求驱动的索引访问。它不包括内部操作,例如通过TTL 索引进行删除或数据段分割以及迁移操作。
限制
$indexStats
必须是聚合管道的第一阶段。$indexStats
不允许在事务中使用。
索引修改重置统计信息
修改现有索引(请参阅 collMod
命令)将重置该索引的统计数据。
例子
例如,集合 orders
包含以下文档:
{ "_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.find( { type: "apparel"} ) db.orders.find( { item: "abc" } ).sort( { quantity: 1 } )
如需查看 orders
集合中索引使用情况的统计信息,请运行以下聚合操作:
db.orders.aggregate( [ { $indexStats: { } } ] )
该操作将返回一个包含每个索引的使用统计信息的文档:
{ "name" : "item_1_quantity_1", "key" : { "item" : 1, "quantity" : 1 }, "host" : "examplehost.local:27018", "accesses" : { "ops" : NumberLong(1), "since" : ISODate("2020-02-10T21:11:23.059Z") }, "shard" : "shardA", // Available starting in MongoDB 4.2.4 if run on sharded cluster "spec" : { // Available starting in MongoDB 4.2.4 "v" : 2, "key" : { "item" : 1, "quantity" : 1 }, "name" : "item_1_quantity_1" } } { "name" : "item_1_price_1", "key" : { "item" : 1, "price" : 1 }, "host" : "examplehost.local:27018", "accesses" : { "ops" : NumberLong(1), "since" : ISODate("2020-02-10T21:11:23.233Z") }, "shard" : "shardA", // Available starting in MongoDB 4.2.4 if run on sharded cluster "spec" : { // Available starting in MongoDB 4.2.4 "v" : 2, "key" : { "item" : 1, "price" : 1 }, "name" : "item_1_price_1" } } { "name" : "item_1", "key" : { "item" : 1 }, "host" : "examplehost.local:27018", "accesses" : { "ops" : NumberLong(0), "since" : ISODate("2020-02-10T21:11:22.947Z") }, "shard" : "shardA", // Available starting in MongoDB 4.2.4 if run on sharded cluster "spec" : { // Available starting in MongoDB 4.2.4 "v" : 2, "key" : { "item" : 1 }, "name" : "item_1" } } { "name" : "_id_", "key" : { "_id" : 1 }, "host" : "examplehost.local:27018", "accesses" : { "ops" : NumberLong(0), "since" : ISODate("2020-02-10T21:11:18.298Z") }, "shard" : "shardA", // Available starting in MongoDB 4.2.4 if run on sharded cluster "spec" : { // Available starting in MongoDB 4.2.4 "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } }