標籤:hint explain mongodb
一、explain函數
explain函數可以提供大量查詢相關的資訊,如果是慢查詢,它最重要的診斷工具。例如:
在有索引的欄位上查詢:
> db.post.find({"loc.city":"ny"}).explain() { "cursor" : "BtreeCursor loc.city_1", "isMultiKey" : false, "n" : 0, "nscannedObjects" : 0, "nscanned" : 0, "nscannedObjectsAllPlans" : 0, "nscannedAllPlans" : 0, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 1, "indexBounds" : { "loc.city" : [ [ "ny", "ny" ] ] }, "server" : "localhost.localdomain:27017", "filterSet" : false } >
在沒有索引的的欄位上查詢:
> db.post.find({"name":"joe"}).explain() { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 2, "nscannedObjects" : 15, "nscanned" : 15, "nscannedObjectsAllPlans" : 15, "nscannedAllPlans" : 15, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 0, "server" : "localhost.localdomain:27017", "filterSet" : false } >
對比上面兩個查詢,對explain結果中的欄位的解釋:
“cursor”:“BasicCursor”表示本次查詢沒有使用索引;“BtreeCursor loc.city_1 ”表示使用了loc.city上的索引;
“isMultikey”表示是否使用了多鍵索引;
“n”:本次查詢返回的文檔數量;
“nscannedObjects”:表示按照索引指標去磁碟上實際尋找實際文檔的次數;
”nscanned“:如果沒有索引,這個數字就是尋找過的索引條目數量;
“scanAndOrder”:是否對結果集進行了排序;
“indexOnly”:是否利用索引就能完成索引;
“nYields”:如果在查詢的過程中有寫操作,查詢就會暫停;這個欄位代表在查詢中因寫操作而暫停次數;
“ millis”:本次查詢花費的次數,數字越小說明查詢的效率越高;
“indexBounds”:這個欄位描述索引的使用方式,給出索引遍曆的範圍。
"filterSet" : 是否使用和索引過濾;
二、hint函數
如果發現MongoDB使用的索引和自己企望的索引不一致。,可以使用hit函數強制MongoDB使用特定的索引。例如
>db.users.find({“age”:1,”username”:/.*/}).hint({“username”:1,”age”:1})
本文出自 “緣隨心愿” 部落格,請務必保留此出處http://281816327.blog.51cto.com/907015/1601477
【MongoDB學習筆記24】MongoDB的explain和hint函數