OPTIONS
翻译或纠错本页面

分析查询性能

The explain() cursor method allows you to inspect the operation of the query system. This method is useful for analyzing the efficiency of queries, and for determining how the query uses the index. The explain() method tests the query operation, and not the timing of query performance. Because explain() attempts multiple query plans, it does not reflect an accurate timing of query performance.

评估查询的性能

想要使用 explain() 方法,可以在 find() 返回的游标上来调用这个方法。

示例

Evaluate a query on the type field on the collection inventory that has an index on the type field.

db.inventory.find( { type: 'food' } ).explain()

思考这个结果:

{
  "cursor" : "BtreeCursor type_1",
  "isMultiKey" : false,
  "n" : 5,
  "nscannedObjects" : 5,
  "nscanned" : 5,
  "nscannedObjectsAllPlans" : 5,
  "nscannedAllPlans" : 5,
  "scanAndOrder" : false,
  "indexOnly" : false,
  "nYields" : 0,
  "nChunkSkips" : 0,
  "millis" : 0,
  "indexBounds" : { "type" : [
                                [ "food",
                                  "food" ]
                             ] },
  "server" : "mongodbo0.example.net:27017" }

The BtreeCursor value of the cursor field indicates that the query used an index.

这个查询返回了5个文档,和 n 字段所显示的一样。

为了返回这5个文档,正如 nscanned 字段显示的那样,查询在索引中扫描了5个文档,然后如 nscannedObjects 字段所显示的那样,在集合中读取了5个完整的文档。

如果没有索引,这个查询想要返回这5个文档的话,则会读取了整个集合。

查看 Explain Results 方法来获取全部关于输出的细节。

比较索引的性能

想要手动的比较一个使用多个索引的查询的性能,你可以同时使用 hint() 方法和 ~cursor.explain() 方法。

示例

Evaluate a query using different indexes:

db.inventory.find( { type: 'food' } ).hint( { type: 1 } ).explain()
db.inventory.find( { type: 'food' } ).hint( { type: 1, name: 1 } ).explain()

这些返回使用各自索引的查询的执行统计。

注解

如果你使用不包含 hint()explain() 方法,查询优化器在返回查询统计之前会重新评估这个查询并且再次执行多重索引。

想要获取更多关于解释输出的详情,请参见 Explain Results