2012-03-14 176 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" 
     ] 
    ] 
} 
}