Measure Index Use

Get Index Access Information with $indexStats

Use the $indexStats aggregation stage to get statisticsregarding the use of each index for a collection. For example, thefollowing aggregation operation returns statistics on the index use onthe orders collection:

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

See also

$indexStats

Return Query Plan with explain()

Use the db.collection.explain() or thecursor.explain() method in executionStats mode to return statistics about thequery process, including the index used, the number of documentsscanned, and the time the query takes to process in milliseconds.

Run db.collection.explain() or the cursor.explain()method in allPlansExecutionmode to view partial execution statistics collected during planselection.

See also

planCacheKey

Control Index Use with hint()

To force MongoDB to use a particular index for adb.collection.find() operation, specify the index with thehint() method. Append the hint()method to the find() method. Consider thefollowing example:

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

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

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

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

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

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

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

Index Metrics

In addition to the $indexStats aggregation stage, MongoDBprovides various index statistics that you may want to consider whenanalyzing index use for your database:

In the output of serverStatus:metrics.queryExecutor.scannedmetrics.operation.scanAndOrder
In the output of collStats:totalIndexSizeindexSizes
In the output of dbStats:dbStats.indexesdbStats.indexSize