Database 为什么MongoDB不使用复合索引进行查询?

Database 为什么MongoDB不使用复合索引进行查询?,database,mongodb,indexing,Database,Mongodb,Indexing,以下是我为该集合提供的复合索引和单一索引: ///db.Collection.getIndexes() /* 1 */ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "service.Collection" }, /* 2 */ {

以下是我为该集合提供的复合索引和单一索引:

///db.Collection.getIndexes()
/* 1 */
{
    "v" : 2,
    "key" : {
        "_id" : 1
    },
    "name" : "_id_",
    "ns" : "service.Collection"
},

/* 2 */
{
    "v" : 2,
    "key" : {
        "FirstId" : 1,
        "SecondId" : 1,
        "CreationTime" : -1
    },
    "name" : "FirstIdSecondIdCreationTime",
    "collation" : {
        "locale" : "en",
        "caseLevel" : false,
        "caseFirst" : "off",
        "strength" : 1,
        "numericOrdering" : false,
        "alternate" : "non-ignorable",
        "maxVariable" : "punct",
        "normalization" : false,
        "backwards" : false,
        "version" : "57.1"
    },
    "ns" : "service.Collection"
},

/* 3 */
{
    "v" : 2,
    "key" : {
        "CreationTime" : 1
    },
    "name" : "CreationTime",
    "collation" : {
        "locale" : "en",
        "caseLevel" : false,
        "caseFirst" : "off",
        "strength" : 1,
        "numericOrdering" : false,
        "alternate" : "non-ignorable",
        "maxVariable" : "punct",
        "normalization" : false,
        "backwards" : false,
        "version" : "57.1"
    },
    "ns" : "service.Collection"
}
预期结果是使用
firstIDSecondCreationTime
索引进行IXSCAN:

///service.Collection.find({ FirstId: "771367b7-4bef-49ab-bda1-6230254c6349", ///SecondId: "3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f" })
///   .projection({})
///   .sort({_id:-1}).hint("FirstIdSecondIdCreationTime").explain('executionStats')

{
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "service.Collection",
        "indexFilterSet" : false,
        "parsedQuery" : {
            "$and" : [
                {
                    "FirstId" : {
                        "$eq" : "771367b7-4bef-49ab-bda1-6230254c6349"
                    }
                },
                {
                    "SecondId" : {
                        "$eq" : "3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f"
                    }
                }
            ]
        },
        "winningPlan" : {
            "stage" : "SORT",
            "sortPattern" : {
                "_id" : -1
            },
            "inputStage" : {
                "stage" : "SORT_KEY_GENERATOR",
                "inputStage" : {
                    "stage" : "FETCH",
                    "filter" : {
                        "$and" : [
                            {
                                "FirstId" : {
                                    "$eq" : "771367b7-4bef-49ab-bda1-6230254c6349"
                                }
                            },
                            {
                                "SecondId" : {
                                    "$eq" : "3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f"
                                }
                            }
                        ]
                    },
                    "inputStage" : {
                        "stage" : "IXSCAN",
                        "keyPattern" : {
                            "FirstId" : 1,
                            "SecondId" : 1,
                            "CreationTime" : -1
                        },
                        "indexName" : "FirstIdSecondIdCreationTime",
                        "collation" : {
                            "locale" : "en",
                            "caseLevel" : false,
                            "caseFirst" : "off",
                            "strength" : 1,
                            "numericOrdering" : false,
                            "alternate" : "non-ignorable",
                            "maxVariable" : "punct",
                            "normalization" : false,
                            "backwards" : false,
                            "version" : "57.1"
                        },
                        "isMultiKey" : false,
                        "multiKeyPaths" : {
                            "FirstId" : [ ],
                            "SecondId" : [ ],
                            "CreationTime" : [ ]
                        },
                        "isUnique" : false,
                        "isSparse" : false,
                        "isPartial" : false,
                        "indexVersion" : 2,
                        "direction" : "forward",
                        "indexBounds" : {
                            "FirstId" : [
                                "[MinKey, MaxKey]"
                            ],
                            "SecondId" : [
                                "[MinKey, MaxKey]"
                            ],
                            "CreationTime" : [
                                "[MaxKey, MinKey]"
                            ]
                        }
                    }
                }
            }
        },
        "rejectedPlans" : [ ]
    },
    "executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 1,
        "executionTimeMillis" : 5491,
        "totalKeysExamined" : 856730,
        "totalDocsExamined" : 856730,
        "executionStages" : {
            "stage" : "SORT",
            "nReturned" : 1,
            "executionTimeMillisEstimate" : 5261,
            "works" : 856734,
            "advanced" : 1,
            "needTime" : 856732,
            "needYield" : 0,
            "saveState" : 6697,
            "restoreState" : 6697,
            "isEOF" : 1,
            "invalidates" : 0,
            "sortPattern" : {
                "_id" : -1
            },
            "memUsage" : 432,
            "memLimit" : 33554432,
            "inputStage" : {
                "stage" : "SORT_KEY_GENERATOR",
                "nReturned" : 1,
                "executionTimeMillisEstimate" : 5201,
                "works" : 856732,
                "advanced" : 1,
                "needTime" : 856730,
                "needYield" : 0,
                "saveState" : 6697,
                "restoreState" : 6697,
                "isEOF" : 1,
                "invalidates" : 0,
                "inputStage" : {
                    "stage" : "FETCH",
                    "filter" : {
                        "$and" : [
                            {
                                "FirstId" : {
                                    "$eq" : "771367b7-4bef-49ab-bda1-6230254c6349"
                                }
                            },
                            {
                                "SecondId" : {
                                    "$eq" : "3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f"
                                }
                            }
                        ]
                    },
                    "nReturned" : 1,
                    "executionTimeMillisEstimate" : 5131,
                    "works" : 856731,
                    "advanced" : 1,
                    "needTime" : 856729,
                    "needYield" : 0,
                    "saveState" : 6697,
                    "restoreState" : 6697,
                    "isEOF" : 1,
                    "invalidates" : 0,
                    "docsExamined" : 856730,
                    "alreadyHasObj" : 0,
                    "inputStage" : {
                        "stage" : "IXSCAN",
                        "nReturned" : 856730,
                        "executionTimeMillisEstimate" : 820,
                        "works" : 856731,
                        "advanced" : 856730,
                        "needTime" : 0,
                        "needYield" : 0,
                        "saveState" : 6697,
                        "restoreState" : 6697,
                        "isEOF" : 1,
                        "invalidates" : 0,
                        "keyPattern" : {
                            "FirstId" : 1,
                            "SecondId" : 1,
                            "CreationTime" : -1
                        },
                        "indexName" : "FirstIdSecondIdCreationTime",
                        "collation" : {
                            "locale" : "en",
                            "caseLevel" : false,
                            "caseFirst" : "off",
                            "strength" : 1,
                            "numericOrdering" : false,
                            "alternate" : "non-ignorable",
                            "maxVariable" : "punct",
                            "normalization" : false,
                            "backwards" : false,
                            "version" : "57.1"
                        },
                        "isMultiKey" : false,
                        "multiKeyPaths" : {
                            "FirstId" : [ ],
                            "SecondId" : [ ],
                            "CreationTime" : [ ]
                        },
                        "isUnique" : false,
                        "isSparse" : false,
                        "isPartial" : false,
                        "indexVersion" : 2,
                        "direction" : "forward",
                        "indexBounds" : {
                            "FirstId" : [
                                "[MinKey, MaxKey]"
                            ],
                            "SecondId" : [
                                "[MinKey, MaxKey]"
                            ],
                            "CreationTime" : [
                                "[MaxKey, MinKey]"
                            ]
                        },
                        "keysExamined" : 856730,
                        "seeks" : 1,
                        "dupsTested" : 0,
                        "dupsDropped" : 0,
                        "seenInvalidated" : 0,
                        "indexDef" : {
                            "indexName" : "FirstIdSecondIdCreationTime",
                            "isMultiKey" : false,
                            "multiKeyPaths" : {
                                "FirstId" : [ ],
                                "SecondId" : [ ],
                                "CreationTime" : [ ]
                            },
                            "keyPattern" : {
                                "FirstId" : 1,
                                "SecondId" : 1,
                                "CreationTime" : -1
                            },
                            "isUnique" : false,
                            "isSparse" : false,
                            "isPartial" : false,
                            "direction" : "forward"
                        }
                    }
                }
            }
        }
但实际结果是COLLSCAN的速度超过8000毫秒:

 "event": {
  "dataset": "mongodb.log",
  "module": "mongodb"
},
"service": {
  "type": "mongodb"
},
"message": "command service.Collection command: find { find: \"Collection\", 
filter: { FirstId: \"771367b7-4bef-49ab-bda1-6230254c6349\", SecondId: \"3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f\" }, sort: { CreationTime: -1 }, limit: 1, 
  planSummary: COLLSCAN keysExamined:0 docsExamined:784787 hasSortStage:1 cursorExhausted:1 numYields:6175 nreturned:1 reslen:677 
  locks:{ Global: { acquireCount: { r: 12352 } }, Database: { acquireCount: { r: 6176 } }, Collection: { acquireCount: { r: 6176 } } } protocol:op_msg 8441ms",
"mongodb.docsExamined": 784787,
"fileset": {
  "name": "log"
},
为什么我要使用
firstIDSecondCreationTime
复合索引进行并置扫描而不是IXScan?有没有办法更改我的索引/我的查询以加快查询速度


根据评论中的建议,我已经运行了
explain(“allPlansExecution”)


能否请您按前导索引(即firstId、secondId和creationTime)按相同顺序排序,并查看是否使用索引。它将给出前导索引字段是否也应该排序的想法。

没有自动考虑“FirstIDSecondCreationTime”索引,因为它是使用排序规则创建的,并且查询在运行时没有排序规则

使用游标方法为查询指定与索引相同的排序规则

使用该索引的5.5秒运行时间也相当慢。
如果您在
{FirstId:1,SecondId:1,{u id:1}
上创建索引,以便查询执行器可以使用索引来满足排序而不是内存中的排序,则该查询可能会有所改进。

尝试使用explain with
allPlansExecution
并且没有提示来查看各种计划的比较情况。要解释
所有计划执行的结果,我猜获胜的计划是通过
第一个id
第二个id
进行筛选,并按
\u id
排序?为什么一句话都没有提到
firstIDSecondCreationTime
?这个计划甚至都没有实施……谢谢你的建议!以下是和的结果,它们工作得太好了(0ms):。我不知道我将如何使用这些信息,现在我已经做到了。。。查询执行器可以使用索引*满足排序*而不是内存排序,这是什么意思?如果索引中的键按照相等排序范围排序,即索引包含要查询的字段以及要排序的字段,并且查询匹配离散值的字段位于索引规范中的排序字段之前,查询执行器可以保证扫描索引将找到已排序顺序的文档,因此它可以完全跳过内存中的排序阶段。看看这个
///db.Collection.find({ FirstId: "771367b7-4bef-49ab-bda1-6230254c6349", ///SecondId: "3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f" })
///   .projection({})
///   .sort({_id:-1}).explain('allPlansExecution')
{
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "service.Collection",
        "indexFilterSet" : false,
        "parsedQuery" : {
            "$and" : [
                {
                    "FirstId" : {
                        "$eq" : "771367b7-4bef-49ab-bda1-6230254c6349"
                    }
                },
                {
                    "SecondId" : {
                        "$eq" : "3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f"
                    }
                }
            ]
        },
        "winningPlan" : {
            "stage" : "FETCH",
            "filter" : {
                "$and" : [
                    {
                        "FirstId" : {
                            "$eq" : "771367b7-4bef-49ab-bda1-6230254c6349"
                        }
                    },
                    {
                        "SecondId" : {
                            "$eq" : "3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f"
                        }
                    }
                ]
            },
            "inputStage" : {
                "stage" : "IXSCAN",
                "keyPattern" : {
                    "_id" : 1
                },
                "indexName" : "_id_",
                "isMultiKey" : false,
                "multiKeyPaths" : {
                    "_id" : [ ]
                },
                "isUnique" : true,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 2,
                "direction" : "backward",
                "indexBounds" : {
                    "_id" : [
                        "[MaxKey, MinKey]"
                    ]
                }
            }
        },
        "rejectedPlans" : [ ]
    },
    "executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 1,
        "executionTimeMillis" : 5408,
        "totalKeysExamined" : 856748,
        "totalDocsExamined" : 856748,
        "executionStages" : {
            "stage" : "FETCH",
            "filter" : {
                "$and" : [
                    {
                        "FirstId" : {
                            "$eq" : "771367b7-4bef-49ab-bda1-6230254c6349"
                        }
                    },
                    {
                        "SecondId" : {
                            "$eq" : "3bffb3cd-fb5e-43e5-abd1-e0b48c97f78f"
                        }
                    }
                ]
            },
            "nReturned" : 1,
            "executionTimeMillisEstimate" : 4862,
            "works" : 856749,
            "advanced" : 1,
            "needTime" : 856747,
            "needYield" : 0,
            "saveState" : 6694,
            "restoreState" : 6694,
            "isEOF" : 1,
            "invalidates" : 0,
            "docsExamined" : 856748,
            "alreadyHasObj" : 0,
            "inputStage" : {
                "stage" : "IXSCAN",
                "nReturned" : 856748,
                "executionTimeMillisEstimate" : 1220,
                "works" : 856749,
                "advanced" : 856748,
                "needTime" : 0,
                "needYield" : 0,
                "saveState" : 6694,
                "restoreState" : 6694,
                "isEOF" : 1,
                "invalidates" : 0,
                "keyPattern" : {
                    "_id" : 1
                },
                "indexName" : "_id_",
                "isMultiKey" : false,
                "multiKeyPaths" : {
                    "_id" : [ ]
                },
                "isUnique" : true,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 2,
                "direction" : "backward",
                "indexBounds" : {
                    "_id" : [
                        "[MaxKey, MinKey]"
                    ]
                },
                "keysExamined" : 856748,
                "seeks" : 1,
                "dupsTested" : 0,
                "dupsDropped" : 0,
                "seenInvalidated" : 0
            }
        },
        "allPlansExecution" : [ ]
    }
}