db.post.find({ loc.city : n..."/>
溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

【MongoDB學習筆記24】MongoDB的explain和hint函數(shù)

發(fā)布時間:2020-09-06 18:09:14 來源:網(wǎng)絡 閱讀:1735 作者:StanlyCheng 欄目:MongoDB數(shù)據(jù)庫

一、explain函數(shù)

explain函數(shù)可以提供大量查詢相關的信息,如果是慢查詢,它最重要的診斷工具。例如:

在有索引的字段上查詢:

> 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”:本次查詢返回的文檔數(shù)量;

“nscannedObjects”:表示按照索引指針去磁盤上實際查找實際文檔的次數(shù);

”nscanned“:如果沒有索引,這個數(shù)字就是查找過的索引條目數(shù)量;

“scanAndOrder”:是否對結果集進行了排序;

“indexOnly”:是否利用索引就能完成索引;

“nYields”:如果在查詢的過程中有寫操作,查詢就會暫停;這個字段代表在查詢中因寫操作而暫停的次數(shù);

“ millis”:本次查詢花費的次數(shù),數(shù)字越小說明查詢的效率越高;

“indexBounds”:這個字段描述索引的使用情況,給出索引遍歷的范圍。

"filterSet" : 是否使用和索引過濾;

 

二、hint函數(shù)

如果發(fā)現(xiàn)MongoDB使用的索引和自己企望的索引不一致。,可以使用hit函數(shù)強制MongoDB使用特定的索引。例如

>db.users.find({“age”:1,”username”:/.*/}).hint({“username”:1,”age”:1})


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI