度量索引使用情况
使用$indexStats
使用$indexStats
聚合阶段可以获取关于集合中每个索引使用的统计信息。例如,以下聚合操作返回了关于 orders
集合索引使用的统计信息
db.orders.aggregate( [ { $indexStats: { } } ] )
使用 explain()
返回查询计划
使用 db.collection.explain()
或 cursor.explain()
方法在 executionStats 模式下返回查询过程的统计信息,包括使用的索引、扫描的文档数量以及查询处理所需的时间(以毫秒为单位)。
在 db.collection.explain()
或 cursor.explain()
方法在 allPlansExecution 模式下运行,以查看在计划选择过程中收集的部分执行统计信息。
使用 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")
或者,将hint()
方法附加到db.collection.explain().find()
:
db.people.explain("executionStats").find( { name: "John Doe", zipcode: { $gt: "63000" } } ).hint( { zipcode: 1 } )
将$natural
运算符指定给hint()
方法以防止MongoDB使用任何索引
db.people.find( { name: "John Doe", zipcode: { $gt: "63000" } } ).hint( { $natural: 1 } )
索引指标
除了$indexStats
聚合阶段之外,MongoDB还提供了各种索引统计信息,您可以在分析数据库的索引使用时考虑这些信息
在
serverStatus
命令的输出中:在
collStats
命令的输出中:在
dbStats
命令的输出中: