温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

【MongoDB学习笔记24】MongoDB的explain和hint函数

发布时间:2020-09-06 18:09:14 来源:网络 阅读:1729 作者:StanlyCheng 栏目: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})


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI