2016-10-17 33 views
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 }]" 
        ] 
      } 
    } 
}, 

回答

2

我使用对象似乎从来没有这个还挺比较。也许MongoDB没有正确处理它。

为了找到你想要的范围内,你可以尝试:

db.DocumentWithCompoundKeyCollection.find({ "_id.Part1" : { $gte : 1, $lte : 3 } }) 
$gte$lte

更多信息,可以发现here

+0

感谢andresk但不幸的是我的代码是用另一种模块,它是依赖在这个模式和查询模式(所以我不能改变它)。 –