我有一个场景,我的" _id"字段包含一个嵌入的文档,当我对嵌入文档中的字段使用时,我看到了比较运算符($ gte / $ lte)的奇怪行为。
e.g。考虑下面的集合,其中有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":{" Part1":1}," $ lte&# 34;:{" Part1":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 }]"
]
}
}
},
答案 0 :(得分:2)
我似乎永远不会使用对象进行这种比较。也许MongoDB没有正确处理它。
为了找到你想要的范围,你可以尝试:
db.DocumentWithCompoundKeyCollection.find({ "_id.Part1" : { $gte : 1, $lte : 3 } })
$gte
和$lte
的更多信息可以找到here