使用索引列

时间:2017-09-13 13:47:22

标签: mongodb mongodb-query

我正在尝试优化我的查询,并发现在非索引列上使用 $ in 时,性能似乎比在索引列上更快。

例如: 我在 myCollection 上添加了一个索引: {" entryVals.col1" :1}

确认: db.myCollection.getIndexes() 返回:

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "myDb.myCollection"
        },
        {
                "v" : 2,
                "key" : {
                        "entryVals.col1" : 1
                },
                "name" : "entryVals.col1_1",
                "ns" : "myDb.myCollection"
        } ]

然后我在索引和非索引列上运行带有查询的计数(打印时间)。

依靠索引列

var a = new Date().getTime();
db.myCollection.count({"entryVals.col1": {$in:["a","b","c","d"]}});
new Date().getTime() - a;

返回 96(以毫秒为单位)

依靠非索引列

var a = new Date().getTime();
db.myCollection.count({"entryVals.col2": {$in:["a","b","c","d"]}}); 
new Date().getTime() - a;

返回 60(以毫秒为单位)

请记住,我多次运行查询并取平均值(几乎没有异常)。

是否有人能够帮助我了解为什么被编入索引的列上的查询速度较慢?

提前致谢。

解释

依靠索引列

db.myCollection.explain().count({"entryVals.col1": {$in:["a","b","c","d"]}}) { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "myDb.myCollection", "indexFilterSet" : false, "parsedQuery" : { "entryVals.col1" : { "$in" : [ "a", "b", "c", "d" ] } }, "winningPlan" : { "stage" : "COUNT", "inputStage" : { "stage" : "FETCH", "inputStage" : { "stage" : "IXSCAN", "keyPattern" : { "entryVals.col1" : 1 }, "indexName" : "entryVals.col1_1", "isMultiKey" : false, "multiKeyPaths" : { "entryVals.col1" : [ ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2, "direction" : "forward", "indexBounds" : { "entryVals.col1" : [ "[\"a\", \"a\"]", "[\"b\", \"b\"]", "[\"c\", \"c\"]", "[\"d\", \"d\"]" ] } } } }, "rejectedPlans" : [ ] }, "serverInfo" : { "host" : "obfuscated", "port" : obfuscated, "version" : "3.4.6-1.7", "gitVersion" : "obfuscated" }, "ok" : 1 }

依靠非索引列

db.myCollection.explain().count({"entryVals.col2": {$in:["a","b","c","d"]}}) { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "myDb.myCollection", "indexFilterSet" : false, "parsedQuery" : { "entryVals.col2" : { "$in" : [ "a", "b", "c", "d" ] } }, "winningPlan" : { "stage" : "COUNT", "inputStage" : { "stage" : "COLLSCAN", "filter" : { "entryVals.col2" : { "$in" : [ "a", "b", "c", "d" ] } }, "direction" : "forward" } }, "rejectedPlans" : [ ] }, "serverInfo" : { "host" : "obfuscated", "port" : obfuscated, "version" : "3.4.6-1.7", "gitVersion" : "obfuscated" }, "ok" : 1 }

0 个答案:

没有答案