【发布时间】:2020-03-05 03:51:15
【问题描述】:
我有一个带有索引的 ISODate() 类型字段的数据库(我也尝试过使用字符串字段进行此实验 - 结果相同)。我正在使用 MongoDB (4.x) 的开源版本,当我进行查询/排序以查找最大 _finish_time 时,除非我指定提示,否则不使用索引。
我的查询是:
db.getCollection("test").find({}, { _finish_time: 1}).sort({_finish_time: -1}).limit(1)
解释为:
{
"queryPlanner" : {
"plannerVersion" : 1.0,
"namespace" : "vdm-service-ts-staging.test",
"indexFilterSet" : false,
"parsedQuery" : {
},
"winningPlan" : {
"stage" : "PROJECTION",
"transformBy" : {
"_finish_time" : 1.0
},
"inputStage" : {
"stage" : "SORT",
"sortPattern" : {
"_finish_time" : -1.0
},
"limitAmount" : 1.0,
"inputStage" : {
"stage" : "SORT_KEY_GENERATOR",
"inputStage" : {
"stage" : "COLLSCAN",
"direction" : "forward"
}
}
}
},
"rejectedPlans" : [
]
},
"serverInfo" : {
"host" : "ip-10-82-245-45.us-west-2.compute.internal",
"port" : 27017.0,
"version" : "4.0.1",
"gitVersion" : "54f1582fc6eb01de4d4c42f26fc133e623f065fb"
},
"ok" : 1.0,
"operationTime" : Timestamp(1573220526, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1573220526, 1),
"signature" : {
"hash" : BinData(0, "blIkiGcam87SDdbKeZKex/9JXBU="),
"keyId" : NumberLong(6715502669504446467)
}
}
}
扫描整个集合。当我为可用索引指定提示时,如下所示:
db.getCollection("test").find({}, { _finish_time: 1}).sort({_finish_time: -1}).limit(1).hint("_finish_time")
我得到了查询计划:
{
"queryPlanner" : {
"plannerVersion" : 1.0,
"namespace" : "vdm-service-ts-staging.test",
"indexFilterSet" : false,
"parsedQuery" : {
},
"winningPlan" : {
"stage" : "LIMIT",
"limitAmount" : 1.0,
"inputStage" : {
"stage" : "PROJECTION",
"transformBy" : {
"_finish_time" : 1.0
},
"inputStage" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"_finish_time" : -1.0
},
"indexName" : "_finish_time",
"isMultiKey" : false,
"multiKeyPaths" : {
"_finish_time" : [
]
},
"isUnique" : false,
"isSparse" : true,
"isPartial" : false,
"indexVersion" : 2.0,
"direction" : "forward",
"indexBounds" : {
"_finish_time" : [
"[MaxKey, MinKey]"
]
}
}
}
}
},
"rejectedPlans" : [
]
},
"serverInfo" : {
"host" : "ip-10-82-245-45.us-west-2.compute.internal",
"port" : 27017.0,
"version" : "4.0.1",
"gitVersion" : "54f1582fc6eb01de4d4c42f26fc133e623f065fb"
},
"ok" : 1.0,
"operationTime" : Timestamp(1573220603, 3),
"$clusterTime" : {
"clusterTime" : Timestamp(1573220603, 3),
"signature" : {
"hash" : BinData(0, "qsGhD1DpI306XbqtNZDYVINPid8="),
"keyId" : NumberLong(6715502669504446467)
}
}
}
其中使用索引。我不想在我的查询中添加hint(),我很困惑为什么它拒绝使用索引。
我的索引是稀疏的,不是唯一的。
我尝试了其他索引并四处搜索,但在堆栈溢出或其他地方找不到任何关于此问题的参考。
【问题讨论】:
标签: mongodb performance indexing hint