衡量索引使用 在本页面
- 使用$indexStats度量索引使用
- 使用
explain()
返回查询计划 - 使用
hint()
控制索引使用 - 索引指标
使用$indexStats度量索引使用
使用
$indexStats
聚合阶段获取关于集合中每个索引的使用情况的统计信息。例如,以下聚合操作返回关于orders
集合中索引使用情况的统计信息:
db.orders.aggregate( [ { $indexStats: { } } ] )
也可参考:
使用 explain()
返回查询计划
在executionStats 模式中使用db.collection.explain()
或cursor.explain()
方法返回关于查询过程的统计信息,包括使用的索引、扫描的文档数量以及查询处理所用的时间(以毫秒为单位)。
在allPlansExecution 模式下使用 db.collection.explain()
或cursor.explain()
方法查看计划选择期间收集的部分执行统计信息。
也可参考:
使用hint()
控制索引使用
要强制MongoDB为db.collection.find()
操作使用特定的索引,请使用hint()方法指定该索引。将hint()
方法附加到find()
方法。考虑下面的例子:
代码示例如下:
db.people.find(
{ name: "John Doe", zipcode: { $gt: "63000" } }
).hint( { zipcode: 1 } )
查看使用特定索引的执行统计信息,在db.collection.find()
语句追加的hint()
方法后跟随cursor.explain()
方法,代码示例如下:
db.people.find(
{ name: "John Doe", zipcode: { $gt: "63000" } }
).hint( { zipcode: 1 } ).explain("executionStats")
或者在db.collection.explain().find()
方法后追加hint()
方法。
db.people.explain("executionStats").find(
{ name: "John Doe", zipcode: { $gt: "63000" } }
).hint( { zipcode: 1 } )
在hint()
方法中声明$natural
参数,避免MongoDB在查询过程中使用任何索引。
db.people.find(
{ name: "John Doe", zipcode: { $gt: "63000" } }
).hint( { $natural: 1 } )
索引指标
除了$indexStats
聚合阶段,MongoDB提供了各种索引统计数据,您可能想要考虑分析索引使用您的数据库:
在serverStatus 方法的输出结果中: |
metrics.queryExecutor.scanned 和metrics.operation.scanAndOrder |
在collStats 输出结果中 |
totalIndexSize 和indexSizes |
在dbStats 输出结果中 |
dbStats.indexes 和dbStats.indexSize |
译者:程哲欣
参见
原文 - Measure Index Use