您的位置:首页 > 数据库 > Mongodb

mongodb创建索引

2017-05-26 17:08 148 查看
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,

},
                查询时间明显的提高了很多。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: