mongodb创建索引

1. mongodb中如果查找在1000000数据中,查找某一个数据,如果查找userId为1的我们来看看耗时:
db.visitLog.find({"userId" : 9}).explain()
"executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 2,
        "executionTimeMillis" : 406,
        "totalKeysExamined" : 0,
        "totalDocsExamined" : 1000008,
        "executionStages" : {
            "stage" : "COLLSCAN",
            "filter" : {
                "userId" : {
                    "$eq" : 9
                }
            },
            "nReturned" : 2,
            "executionTimeMillisEstimate" : 354,
            "works" : 1000010,
            "advanced" : 2,
            "needTime" : 1000007,
            "needYield" : 0,
            "saveState" : 7817,
            "restoreState" : 7817,
            "isEOF" : 1,
            "invalidates" : 0,
            "direction" : "forward",
            "docsExamined" : 1000008
        }
                 执行时间406毫秒,注意这里userId为9,也就是数据开始的第九个
"executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 1,
        "executionTimeMillis" : 54700,
        "totalKeysExamined" : 0,
        "totalDocsExamined" : 1000008,
        "executionStages" : {
            "stage" : "COLLSCAN",
            "filter" : {
                "userId" : {
                    "$eq" : 999999
                }
            },
            "nReturned" : 1,
            "executionTimeMillisEstimate" : 375,
            "works" : 1000010,
            "advanced" : 1,
            "needTime" : 1000008,
            "needYield" : 0,
            "saveState" : 7819,
            "restoreState" : 7819,
            "isEOF" : 1,
            "invalidates" : 0,
            "direction" : "forward",
            "docsExamined" : 1000008
        },
        "allPlansExecution" : []
    }

                好了,时间差别很大,因为mongodb从开始一个个查找,所以消耗时间过长

2.创建索引再看看

db.visitLog.ensureIndex({"userId":1})  //创建索引
"executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 1,
        "executionTimeMillis" : 0,
        "totalKeysExamined" : 1,
        "totalDocsExamined" : 1,
        
        },
                查询时间明显的提高了很多。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值