我为正在进行的特定查询创建了围绕多个项目的索引:
{
"v" : 1,
"key" : {
"MODIFIED" : -1,
"state" : 1,
"fail" : 1,
"generated" : 1
},
"ns" : "foo.bar",
"name" : "MODIFIED_-1_state_1_fail_1_generated"
}
但是,当我执行查询时,它似乎并没有使用我的索引。您能否提供一些关于我做错了什么的网站?
谢谢!
db.foo.find( {
"$or": [
{
"MODIFIED": {
"$gt": {
"sec": 1321419600,
"usec": 0
}
}
},
{
"$or": [
{"state": "ca"},
{"state": "ok"}
]
}
],
"$and": [
{"fail": {"$ne": 1}},
{"generated": {"$exists": false}}
]
}).explain();
{
"cursor" : "BasicCursor",
"nscanned" : 464215,
"nscannedObjects" : 464215,
"n" : 0,
"millis" : 7549,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
}
}
最佳答案
您的索引不能用于查询是有充分理由的,我也认为查询本身存在一些问题。它没有命中索引的原因是顺便说一下嵌套的 $or 运算符,但我认为您的实际问题是对 MongoDB 中可用的所有运算符缺乏了解:
首先,您的嵌套 $or 来检查状态是“ca”还是“ok”是不必要的,并且(因为这是您没有达到索引的主要原因)可以替换为 state:{$in:["ca", "ok"]}
做同样的事情。现在您的查询是:
db.foo.find( {
"$or": [
{
"MODIFIED": {
"$gt": {
"sec": 1321419600,
"usec": 0
}
}
},
{
state:{$in:["ca", "ok"]}
}
],
"$and": [
{"fail": {"$ne": 1}},
{"generated": {"$exists": false}}
]
}).explain();
它会影响你的索引。您的第二个问题是不需要顶级 $and 子句。请注意 AND(OR(A, B), AND(C, D)) = AND(OR(A, B), C, D)
。这个查询做同样的事情:
db.foo.find( {
"$or": [
{
"MODIFIED": {
"$gt": {
"sec": 1321419600,
"usec": 0
}
}
},
{
state:{$in:["ca", "ok"]}
}
],
"fail": {"$ne": 1},
"generated": {"$exists": false}
}).explain();
仍然命中索引:
{
"clauses" : [
{
"cursor" : "BtreeCursor MODIFIED_-1_state_1_fail_1_generated_1 multi",
"nscanned" : 0,
"nscannedObjects" : 0,
"n" : 0,
"millis" : 1,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"MODIFIED" : [
[
{
"$maxElement" : 1
},
{
"sec" : 1321419600,
"usec" : 0
}
]
],
"state" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
],
"fail" : [
[
{
"$minElement" : 1
},
1
],
[
1,
{
"$maxElement" : 1
}
]
],
"generated" : [
[
null,
null
]
]
}
},
{
"cursor" : "BasicCursor",
"nscanned" : 0,
"nscannedObjects" : 0,
"n" : 0,
"millis" : 1,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
}
}
],
"nscanned" : 0,
"nscannedObjects" : 0,
"n" : 0,
"millis" : 1
}
希望对您有所帮助!顺便说一句,复合索引中的第一个键以顺序 1 开始,第二个键以 -1 开始稍微更传统一些。请注意,-1 仅用于确定相对于前一个字段的方向。
关于mongodb - 未使用 Mongo 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9280540/