索引使用情况"/>
使用$indesStats查看索引使用情况
在Mongodb的添加索引,可以提高查询的效率。但索引可能会带来一些副作用,如插入和更新数据时,会更新集合中的索引。因此,mongodb中,需要定期查看mongodb索引的使用情况。及时回收不需要的索引。
Mongodb提供了$indexStats命令, 返回当前集合索引的定义和使用信息。如果mongodb开启访问限制,用户需要有clusterMonitor 权限。
在aggregation的pipeline中,添加$indexStats, 查看索引使用情况。
db.collection.aggregation([{$indexStats:{}}])
在返回结果中,包含下面的索引信息
字段名 | 说明 |
key | 索引的字段定义 |
host | 当前mongdb运行的主机和端口信息 |
accesses | 索引使用统计信息。ops 表示索引使用次数;since表示统计开始时间 |
shard | 所在主机的分片信息 |
spec | 索引完整的定义信息 |
building | 当前索引是否正在构建 |
使用$indexStats查看索引时,有下面几个注意事项
- Mongodb 进程重启时,统计信息被重置
- 索引重新创建,更新,删除时,统计信息被重置
- 集合删除时,统计信息也响应的被删除
- $indexStats 必须放在aggregation pipeline的第一个阶段
使用举例
- 使用3条记录,创建一个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.find({type: “apparel”})
db.orders.find({item:”abc”}).sort({quantity: 1})
- 查看索引统计信息
db.orders.aggregate([{$indexStats:{}}])
/* 1 */
{
"name" : "_id_",
"key" : {
"_id" : 1
},
"host" : "WANGJA10-2-W11:27017",
"accesses" : {
"ops" : Long("0"),
"since" : ISODate("2023-11-07T17:23:49.122+08:00")
},
"spec" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
},
/* 2 */
{
"name" : "item_1_quantity_1",
"key" : {
"item" : 1,
"quantity" : 1
},
"host" : "WANGJA10-2-W11:27017",
"accesses" : {
"ops" : Long("1"),
"since" : ISODate("2023-11-07T17:23:55.089+08:00")
},
"spec" : {
"v" : 2,
"key" : {
"item" : 1,
"quantity" : 1
},
"name" : "item_1_quantity_1"
}
},
/* 3 */
{
"name" : "type_1_item_1",
"key" : {
"type" : 1,
"item" : 1
},
"host" : "XXXX:27017",
"accesses" : {
"ops" : Long("0"),
"since" : ISODate("2023-11-07T17:23:55.102+08:00")
},
"spec" : {
"v" : 2,
"key" : {
"type" : 1,
"item" : 1
},
"name" : "type_1_item_1"
}
}
5. 清理现场
db.orders.drop()
更多推荐
使用$indesStats查看索引使用情况
发布评论