2012-03-14 32 views
6

我想弄清楚我必须如何构建查询,以便他们会打我的索引。 我有结构化的,像这样的文件:MongoDB - 与索引嵌套字段的查询

{ "attributes" : { "make" : "Subaru", "color" : "Red" } } 

随着指数:我已经找到db.stuff.ensureIndex({"attributes.make":1})

是使用点符号查询命中索引,而与文档查询没有。

例子:

db.stuff.find({"attributes.make":"Subaru"}).explain() 
{ 
"cursor" : "BtreeCursor attributes.make_1", 
"nscanned" : 2, 
"nscannedObjects" : 2, 
"n" : 2, 
"millis" : 0, 
"nYields" : 0, 
"nChunkSkips" : 0, 
"isMultiKey" : false, 
"indexOnly" : false, 
"indexBounds" : { 
    "attributes.make" : [ 
     [ 
      "Subaru", 
      "Subaru" 
     ] 
    ] 
} 
} 

VS

db.stuff.find({attributes:{make:"Subaru"}}).explain() 
{ 
"cursor" : "BasicCursor", 
"nscanned" : 2, 
"nscannedObjects" : 2, 
"n" : 0, 
"millis" : 1, 
"nYields" : 0, 
"nChunkSkips" : 0, 
"isMultiKey" : false, 
"indexOnly" : false, 
"indexBounds" : { 

} 
} 

是否有一种方式来获得文档样式查询命中索引?原因在于,当从我的持久对象构造查询时,将它们序列化为文档相对于使用点符号的东西要容易得多。

我还会补充一点,我们使用的是一个用Jackson构建的本地数据映射器层。使用类似Morphia的东西有助于正确构造这些查询吗?

回答

7

做了一些更多的挖掘,this thread解释了子文档查询的内容。我上面的问题是,使基于子文档的查询像我需要使用elemMatch的点符号一样。

db.stuff.find({"attributes":{"$elemMatch" : {"make":"Subaru"}}}).explain() 
{ 
"cursor" : "BtreeCursor attributes.make_1", 
"nscanned" : 2, 
"nscannedObjects" : 2, 
"n" : 0, 
"millis" : 2, 
"nYields" : 0, 
"nChunkSkips" : 0, 
"isMultiKey" : false, 
"indexOnly" : false, 
"indexBounds" : { 
    "attributes.make" : [ 
     [ 
      "Subaru", 
      "Subaru" 
     ] 
    ] 
} 
}