开发学院

您的位置:首页>教程>正文

教程正文

MongoDB 分析查询

MongoDB 分析查询

  分析查询是衡量数据库和索引设计效率的一个非常重要的方面。我们将了解常用的$ explain和$提示查询。

使用$explain

  $explain操作符提供有关查询、查询中使用的索引和其他统计信息的信息。当分析索引的优化程度时,它非常有用。

  在最后一章中,我们已经使用以下查询为用户集合创建了关于字段性别和用户名的索引

>db.users.ensureIndex({gender:1,user_name:1})

  我们现在将在以下查询中使用$explain:

>db.users.find({gender:"M"},{user_name:1,_id:0}).explain()

  上述explain()查询返回以下分析结果

{
   "cursor" : "BtreeCursor gender_1_user_name_1",
   "isMultiKey" : false,
   "n" : 1,
   "nscannedObjects" : 0,
   "nscanned" : 1,
   "nscannedObjectsAllPlans" : 0,
   "nscannedAllPlans" : 1,
   "scanAndOrder" : false,
   "indexOnly" : true,
   "nYields" : 0,
   "nChunkSkips" : 0,
   "millis" : 0,
   "indexBounds" : {
      "gender" : [
         [
            "M",
            "M"
         ]
      ],
      "user_name" : [
         [
            {
               "$minElement" : 1
            },
            {
               "$maxElement" : 1
            }
         ]
      ]
   }
}

  我们现在将查看此结果集中的字段

  indexOnly的true值指示此查询已使用索引。

  cursor字段指定使用的游标类型。BTreeCursor类型表示使用了索引,并给出了使用的索引的名称。BasicCursor表示在不使用任何索引的情况下进行了完整扫描。

  n:表示返回的匹配文档数。

  nscannedObjects表示扫描的文档总数。

  nscanted表示扫描的文档或索引条目的总数。

使用$hint

  $hint强制查询优化器使用指定的索引运行查询。当您想要测试具有不同索引的查询的性能时,这一点特别有用。例如,以下查询指定要用于此查询的字段性别和用户名的索引

>db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1})

  要使用$explain来分析上述查询,请执行以下操作

>db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain()