首页 > 解决方案 > MongoDB 不使用复合索引进行排序阶段

问题描述

我有一个集合,并且我指定了一个复合索引。该索引用于过滤,但是排序是在内存中完成的,我不知道为什么。

我有以下文件:

{ _id :1, 
  accountId: 1234566,
  positionId: 9090,
  eventDateTime: "2021-01-02T09:38:45",
  nonce: 1415,
  event: {
    symbol: "value1"
  }
}

我使用的索引是

db.data.createIndex({"accountId" : 1, "positionId" : 1, "event.symbol" : 1, eventDateTime: -1, "nonce": -1})

我的查询是

db.data.find({"accountId" : 123456, "positionId" : 9090, "event.symbol": { $in :["value1" , "value2", "value3"]}).sort({"eventDateTime" :-1, "nonce": -1})

在使用 explain 之后,我得到了以下计划(缩写):

"executionStats": { 
  "executionSuccess": "true",
   "nReturned" : 9
    "executionTimeMillis" : 0,
     "totalKeysExamined" : 10,
      "totalDocsExamined" : 9,
      "executionStages" : {
        "stage" : "SORT"
        "sortPattern" : {
          "eventDateTime" : -1,
           "nonce" : -1
          },
          "inputStage" : {
            "stage" : "SORT_KEY_GENERATOR"           
             }
              "inputStage" : {
                "stage" : "FETCH"           
                }

                 "inputStage" : {
                   "stage" : "IXSCAN" 
                    "keyPattern" : {
                      "accountId" : 1,
                       "positionId" : 1,
                        "event.symbol" : 1,
                        "eventDateTime" : -1,
                        "nonce" : -1
                     }          
                   }
}

对我来说奇怪的是,如果使用索引:

 db.data.createIndex({"accountId" : 1, "positionId" : 1, eventDateTime: -1, "nonce": -1})

在同一个查询中,排序不在内存中执行。我很难理解正在发生的事情以及第一个索引不起作用的原因。任何帮助将非常感激。

在我也将索引更改为

db.data.createIndex({"accountId" : 1, "positionId" : 1,  eventDateTime: -1, "nonce": -1, "event.symbol" : 1,})

为了匹配 ESR 建议,排序也在内存中执行

标签: mongodbindexing

解决方案


推荐阅读