Docs 菜单

Docs 主页开发应用程序MongoDB Manual

测量索引使用情况

在此页面上

  • 获取索引访问信息 $indexStats
  • 使用以下方法返回查询计划: explain()
  • 控制索引使用 hint()
  • 索引指标

使用 $indexStats 聚合阶段来获取有关每个集合索引的使用情况的统计信息。例如,以下聚合操作会返回针对 orders 集合的索引使用情况的统计信息:

db.orders.aggregate( [ { $indexStats: { } } ] )

提示

另请参阅:

executionStats 模式下使用 db.collection.explain()cursor.explain() 方法返回有关查询进程的统计信息,包括使用的索引、扫描的文档数量以及处理查询所花费的时间(以毫秒为单位)。

AllPlanSexecution 模式下运行 db.collection.explain()cursor.explain() 方法,查看在计划选择期间收集的部分执行统计信息。

提示

另请参阅:

强制 MongoDB 使用特定索引进行 db.collection.find() 操作,请使用 hint() 方法指定该索引。将 hint() 方法附加到 find() 方法。以以下示例为例:

db.people.find(
{ name: "John Doe", zipcode: { $gt: "63000" } }
).hint( { zipcode: 1 } )

要查看特定索引的执行统计信息,请将 hint() 方法附在 db.collection.find()后面,再接上 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 } )

hint() 方法指定 $natural 操作符,防止 MongoDB 使用任何索引:

db.people.find(
{ name: "John Doe", zipcode: { $gt: "63000" } }
).hint( { $natural: 1 } )

$indexStats 聚合阶段之外,MongoDB 还提供各种索引统计信息,而当您在分析数据库的索引使用情况时可能需考虑这些统计信息:

← 管理索引