0
我有一個場景,其中「_id」字段包含嵌入式文檔,並且在針對嵌入式文檔中的字段使用時看到了比較運算符($ gte/$ lte)的奇怪行爲。嵌入式文檔上的MongoDB索引邊界
例如考慮下面的收集有9個文檔,每一個嵌入的文件爲「_id」
db.DocumentWithCompoundKeyCollection.find()
{ "_id" : { "Part1" : 1, "Part2" : 1 }, "SomeValue" : BinData(3,"B8+yWvTV4kS/u3e6Cv8Kcw==") }
{ "_id" : { "Part1" : 1, "Part2" : 2 }, "SomeValue" : BinData(3,"eLS1ONAoGUawW+v+vQdFDQ==") }
{ "_id" : { "Part1" : 1, "Part2" : 3 }, "SomeValue" : BinData(3,"m7WsIyInIEmsgWUMcsJPAw==") }
{ "_id" : { "Part1" : 2, "Part2" : 4 }, "SomeValue" : BinData(3,"z7/2j0g4AUikqS5K1TzZig==") }
{ "_id" : { "Part1" : 2, "Part2" : 5 }, "SomeValue" : BinData(3,"WudfqGYE8U+YwWe3Q0qL1w==") }
{ "_id" : { "Part1" : 2, "Part2" : 6 }, "SomeValue" : BinData(3,"B60SpSmXdUGn6AJDu1JIzg==") }
{ "_id" : { "Part1" : 3, "Part2" : 7 }, "SomeValue" : BinData(3,"xVmhanYiV0+dOdTx7PAZkw==") }
{ "_id" : { "Part1" : 3, "Part2" : 8 }, "SomeValue" : BinData(3,"5NNdVzErt0qephmCMRR1nQ==") }
{ "_id" : { "Part1" : 3, "Part2" : 9 }, "SomeValue" : BinData(3,"mhTiJoHGKkCPUeglCfLUoQ==") }
現在,當我運行一個查詢返回的所有文件其中「Part1」> = 1和「Part1」< = 3,我應該得到所有9個文檔,但mongo只返回6個文檔(所有帶{「Part1」:3 ...}的文檔都被跳過)
db.DocumentWithCompoundKeyCollection.find({ 「_id」:{ 「$ GTE」:{ 「第1部分」:1}, 「$ LTE」:{ 「第1部分」:3}}})
{ "_id" : { "Part1" : 1, "Part2" : 1 }, "SomeValue" : BinData(3,"B8+yWvTV4kS/u3e6Cv8Kcw==") }
{ "_id" : { "Part1" : 1, "Part2" : 2 }, "SomeValue" : BinData(3,"eLS1ONAoGUawW+v+vQdFDQ==") }
{ "_id" : { "Part1" : 1, "Part2" : 3 }, "SomeValue" : BinData(3,"m7WsIyInIEmsgWUMcsJPAw==") }
{ "_id" : { "Part1" : 2, "Part2" : 4 }, "SomeValue" : BinData(3,"z7/2j0g4AUikqS5K1TzZig==") }
{ "_id" : { "Part1" : 2, "Part2" : 5 }, "SomeValue" : BinData(3,"WudfqGYE8U+YwWe3Q0qL1w==") }
{ "_id" : { "Part1" : 2, "Part2" : 6 }, "SomeValue" : BinData(3,"B60SpSmXdUGn6AJDu1JIzg==") }
添加.explain()按預期返回正確的indexBounds,爲什麼最後3個文檔沒有被返回?
索引圖
"winningPlan" : {
"stage" : "FETCH",
"filter" : {
"$and" : [
{
"_id" : {
"$lte" : {
"Part1" : 3
}
}
},
{
"_id" : {
"$gte" : {
"Part1" : 1
}
}
}
]
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"_id" : 1
},
"indexName" : "_id_",
"isMultiKey" : false,
"isUnique" : true,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 1,
"direction" : "forward",
"indexBounds" : {
"_id" : [
"[{ Part1: 1.0 }, { Part1: 3.0 }]"
]
}
}
},
感謝andresk但不幸的是我的代碼是用另一種模塊,它是依賴在這個模式和查詢模式(所以我不能改變它)。 –