Heim  >  Artikel  >  Datenbank  >  MongoDB操作手册CRUD查询性能分析

MongoDB操作手册CRUD查询性能分析

WBOY
WBOYOriginal
2016-06-07 16:06:13899Durchsuche

分析查询性能 explain() cursor方法允许观察查询系统执行的操作。这个方法对于分析高效查询和决定如何使用索引进行查询是十分有用的。这个方法检测的是查询的操作,而不是查询执行时间。因为这个方法尝试多个查询计划,它并不能准确的反映出查询执行时间。

分析查询性能

explain() cursor方法允许观察查询系统执行的操作。这个方法对于分析高效查询和决定如何使用索引进行查询是十分有用的。这个方法检测的是查询的操作,而不是查询执行时间。因为这个方法尝试多个查询计划,它并不能准确的反映出查询执行时间。

评估一个查询的性能

使用explain()方法,调用find()返回的指针的该方法即可。
例:
在type字段创建索引
db.testData.ensureIndex({'type':1});
评估一个在type字段上的查询。
db.testData.find({type:'food'}).explain()
结果如下:
{
"cursor" : "BtreeCursor type_1",
"isMultiKey" : false,
"n" : 3,
"nscannedObjects" : 3,
"nscanned" : 3,
"nscannedObjectsAllPlans" : 3,
"nscannedAllPlans" : 3,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 1,
"nChunkSkips" : 0,
"millis" : 64,
"indexBounds" : {
"type" : [
[
"food",
"food"
]
]
},
"server" : "TT:27017",
"filterSet" : false
}
cursor值为BtreeCursor表名查询使用了索引。
查询返回n=3条记录。
为了返回这五条记录,查询扫描了nscanned=3条记录,然后读到了nscannedObjects=3条完整的记录,如果没有索引,将扫描所有记录。

比较索引查询性能

手动比较一个使用多个字段的查询,可以联合使用hint()和explain()方法。
例:评估使用不同字段的索引
db.testData.find({type:'food'}).hint({type:1}).explain();
结果:
{
"cursor" : "BtreeCursor type_1",
"isMultiKey" : false,
"n" : 3,
"nscannedObjects" : 3,
"nscanned" : 3,
"nscannedObjectsAllPlans" : 3,
"nscannedAllPlans" : 3,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 40,
"indexBounds" : {
"type" : [
[
"food",
"food"
]
]
},
"server" : "TT:27017",
"filterSet" : false
}
db.testData.find( { type: 'food' } ).hint( { type: 1, name: 1 } ).explain();
//这句话执行不成功,待解决
这些返回的统计结果忽略了使用各自的索引的执行的查询。
注意:如果不适用hint()执行explain()方法,查询优化器将重新评估查询,并且在返回查询统计之前运行多索引查询。
更详细的explain输出,查看explain-results。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn