翻译或纠错本页面
  • Indexes >
  • 衡量索引的使用情况

衡量索引的使用情况

On this page

Get Index Access Information with $indexStats

Use $indexStats to get usage statistics about an index.

使用 explain() 返回查询计划(query plan)

在任意游标(例如 查询)后面附加 explain() 方法可以返回一个含有查询过程的统计数据的文档,包括所使用的索引,扫描过的文档数,查询所消耗的毫秒数。

Run db.collection.explain() or the cursor.explain() method in allPlansExecution mode to view partial execution statistics collected during plan selection.

db.collection.explain() provides information on the execution of other operations, such as db.collection.update(). See db.collection.explain() for details.

在任意游标(例如 查询)后面附加 hint() 方法并以索引作为方法参数可以 强制 MongoDB使用指定的索引来匹配查询。请看如下示例:

您可以使用联合使用 hint() and explain() 来逐个对比每个索引的效率。您可以在 hint() 方法中指定 $natural 操作符来避免MongoDB使用 任何 索引(注; 亦即,查询不会使用索引):

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

To view the execution statistics for a specific index, append to the db.collection.find() the hint() method followed by cursor.explain(), e.g.:

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

Or, append hint() method to db.collection.explain().find():

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

Specify the $natural operator to the hint() method to prevent MongoDB from using any index:

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

MongoDB实例的索引使用情况报告

MongoDB提供了一系列关于索引利用情况的度量工具和操作,这在您希望分析数据库中的索引使用情况时可能会需要用到:

serverStatus 的输出结果中:

metrics.queryExecutor.scanned

metrics.operation.scanAndOrder

collStats 的输出结果中:

totalIndexSize

indexSizes

dbStats 的输出结果中:

dbStats.indexes

dbStats.indexSize