mongodb创建索引

来源:互联网 发布:最新司令部升级数据 编辑:程序博客网 时间:2024/05/20 19:45
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,                },
                查询时间明显的提高了很多。



原创粉丝点击