衡量索引使用 在本页面

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

    也可参考:

    $indexStats

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

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

    也可参考:

    planCacheKey

    使用hint()控制索引使用 要强制MongoDB为db.collection.find()操作使用特定的索引,请使用hint()方法指定该索引。将hint()方法附加到find()方法。考虑下面的例子:

    代码示例如下:

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

    查看使用特定索引的执行统计信息,在db.collection.find()语句追加的hint()方法后跟随cursor.explain()方法,代码示例如下:

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

    或者在db.collection.explain().find()方法后追加hint()方法。

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

    hint()方法中声明$natural参数,避免MongoDB在查询过程中使用任何索引。

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

    索引指标 除了$indexStats聚合阶段,MongoDB提供了各种索引统计数据,您可能想要考虑分析索引使用您的数据库:

    serverStatus方法的输出结果中: metrics.queryExecutor.scannedmetrics.operation.scanAndOrder
    collStats输出结果中 totalIndexSizeindexSizes
    dbStats输出结果中 dbStats.indexesdbStats.indexSize

    译者:程哲欣

    参见

    原文 - Measure Index Use