分析查询是衡量数据库和索引设计的有效性的一个非常重要的方式。在这里我们将介绍两个经常使用的$explain和$hint查询。
使用 $explain 操作符
$explain操作符提供有关查询的信息,查询中使用的索引和其他统计信息。它在在分析索引优化情况时非常有用。
在最后一章中,我们已经使用以下查询在users集合的字段:gender 和 user_name 上创建了一个索引:
>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表示扫描的文档总数。
nscanned表示扫描的文档或索引条目的总数。
使用 $hint
$hint操作符强制查询优化器使用指定的索引来运行查询。当要测试具有不同索引的查询的性能时,这就特别有用了。 例如,以下查询指定要用于此查询的gender和user_name字段的索引 -
> 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()
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。