MongoDB索引未被使用

Sat*_*oko 9 indexing mongodb

我有一组带有修改索引的问题.

{
  "v" : 1,
  "key" : {
      "modified" : 1
  },
  "name" : "modified_1",
  "ns" : "app23568387.questions",
  "background" : true,
  "safe" : null
}
Run Code Online (Sandbox Code Playgroud)

但是当我用修改字段查询问题时,mongo不使用此索引.

db.questions.find({modified: ISODate("2016-07-20T20:58:20.662Z")}).explain(true);
Run Code Online (Sandbox Code Playgroud)

它回来了

{
  "cursor" : "BasicCursor",
  "isMultiKey" : false,
  "n" : 0,
  "nscannedObjects" : 19315626,
  "nscanned" : 19315626,
  "nscannedObjectsAllPlans" : 19315626,
  "nscannedAllPlans" : 19315626,
  "scanAndOrder" : false,
  "indexOnly" : false,
  "nYields" : 384889,
  "nChunkSkips" : 0,
  "millis" : 43334,
  "allPlans" : [ 
      {
          "cursor" : "BasicCursor",
          "isMultiKey" : false,
          "n" : 0,
          "nscannedObjects" : 19315626,
          "nscanned" : 19315626,
          "scanAndOrder" : false,
          "indexOnly" : false,
          "nChunkSkips" : 0
      }
  ],
  "server" : "c387.candidate.37:10387",
  "filterSet" : false,
  "stats" : {
      "type" : "COLLSCAN",
      "works" : 19624020,
      "yields" : 384889,
      "unyields" : 384889,
      "invalidates" : 3,
      "advanced" : 0,
      "needTime" : 19315627,
      "needFetch" : 0,
      "isEOF" : 1,
      "docsTested" : 19315626,
      "children" : []
  }
}
Run Code Online (Sandbox Code Playgroud)

当我使用时hint(),mongo会抛出错误bad hint.我有另一个文件夹集合,它们具有完全相同的索引,查询使用索引.(返回"cursor" : "BtreeCursor modified_1"explain())

问题和文件夹之间可能有什么区别?即使getIndexes()返回索引,索引是否可能"被破坏" ?如果是这样,我该怎么做才能解决它?

anh*_*hlc 2

看来您的索引没有完全在后台构建。您可以使用 db.currentOp() 命令来检查:

https://docs.mongodb.com/v3.0/reference/method/db.currentOp/#currentop-index-creation

另请检查 mongod.log 以查看索引构建过程中的任何错误。

修复的简单方法是删除索引并重新创建它

  • 这是有可能的。(a) “badhint”响应与 (2) 该索引由“getIndexes()”返回的声明之间的不一致强烈表明索引创建过程存在问题。相关建议:如果 OP 正在查询具有最终一致性的副本集,并且查询正在命中辅助数据库,那么问题可能是索引尚未在辅助数据库上成功构建。 (2认同)