Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$indexStats(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$indexStats

返回集合中每个索引使用情况的统计信息。如果在运行时存在访问控制,请至少以具有 clusterMonitor 角色的用户身份进行验证。

$indexStats阶段接受空文档并具有以下事务语法:

{ $indexStats: { } }

对于每个索引,返回文档包含以下字段:

输出字段
说明
name
索引名称。

索引密钥规范。

另请参阅: spec。

mongod进程的主机名和端口。

有关索引使用的统计信息:

  • ops 是使用索引的操作次数。

  • since 是 MongoDB 收集统计数据的时间。

主机关联的分片的名称

仅适用于分片群集。

4.2.4 版本新增

索引的完整规范文档,其中包括索引键规范文档。

仅当值为 时才包含索引选项hiddentrue

4.2.4 版本新增

指示索引当前是否正在构建。

仅当 true 时才可用。

4.2.4 版本新增

索引的统计数据将在 mongod 重启或索引删除和重新创建时重置。

注意

在 3.2.3 版本之前,ops 字段值不包括使用索引的 $matchmapReduce 操作。

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_"
}
}
← $group(聚合)

在此页面上