$indexStats (aggregation)

Definition

  • $indexStats

New in version 3.2.

Returns statistics regarding the use of each index for thecollection. If running with access control, the user must have privileges that includeindexStats action.

The $indexStats stage takes an empty document and hasthe following syntax:

  1. { $indexStats: { } }

The return document includes the following fields:

Output FieldDescriptionnameIndex name.keyIndex key specification.hostThe hostname and port of the mongod process.accessesStatistics on the index use:

  • ops is the number of operations that used theindex.
  • since is the time from which MongoDB gathered thestatistics.

Statistics for an index will be reset on mongod restartor index drop and recreation.

Note

Prior to version 3.2.3, the ops field value did not include$match or mapReduce operations that use indexes.

Behavior

The statistics reported by the accesses field only includes indexaccess driven by user requests. It does not include internal operations likedeletion via TTL Indexes or chunk split and migration operations.

$indexStats must be the first stage in an aggregation pipeline.

$indexStats is not allowed in transactions.

Example

For example, a collection orders contains the following documents:

  1. { "_id" : 1, "item" : "abc", "price" : 12, "quantity" : 2, "type": "apparel" }
  2. { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "type": "electronics" }
  3. { "_id" : 3, "item" : "abc", "price" : 10, "quantity" : 5, "type": "apparel" }

Create the following two indexes on the collection:

  1. db.orders.createIndex( { item: 1, quantity: 1 } )
  2. db.orders.createIndex( { type: 1, item: 1 } )

Run some queries against the collection:

  1. db.orders.find( { type: "apparel"} )
  2. db.orders.find( { item: "abc" } ).sort( { quantity: 1 } )

To view statistics on the index use on the orders collection,run the following aggregation operation:

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

The operation returns a document that contains usage statistics foreach index:

  1. {
  2. "name" : "item_1_quantity_1",
  3. "key" : {
  4. "item" : 1,
  5. "quantity" : 1
  6. },
  7. "host" : "examplehost.local:27017",
  8. "accesses" : {
  9. "ops" : NumberLong(1),
  10. "since" : ISODate("2015-10-02T14:31:53.685Z")
  11. }
  12. }
  13. {
  14. "name" : "_id_",
  15. "key" : {
  16. "_id" : 1
  17. },
  18. "host" : "examplehost.local:27017",
  19. "accesses" : {
  20. "ops" : NumberLong(0),
  21. "since" : ISODate("2015-10-02T14:31:32.479Z")
  22. }
  23. }
  24. {
  25. "name" : "type_1_item_1",
  26. "key" : {
  27. "type" : 1,
  28. "item" : 1
  29. },
  30. "host" : "examplehost.local:27017",
  31. "accesses" : {
  32. "ops" : NumberLong(1),
  33. "since" : ISODate("2015-10-02T14:31:58.321Z")
  34. }
  35. }