2012-04-18 90 views
9

的指標MongoDB的指標幫助在http://www.mongodb.org/display/DOCS/Indexes頁面沒有提到$ elemMatch並且由於它天天在我的2M +對象集合添加索引我想我會問這個:

我做了查詢關鍵詞,比如:

{ lc: "eng", group: "xyz", indices: { $elemMatch: { text: "as", pos: { $gt: 1 } } } } 

如果我添加一個索引

{lc:1, group:1, indices.text:1, indices.pos:1} 

將這個查詢與$ elemMatch組件能夠通過索引完全運行?

回答

15

根據您的查詢,我想,你的文件看起來像這樣:

{ 
    "_id" : 1, 
    "lc" : "eng", 
    "group" : "xyz", 
    "indices" : [ 
     { 
      "text" : "as", 
      "pos" : 2 
     }, 
     { 
      "text" : "text", 
      "pos" : 4 
     } 
    ] 
} 

我創建了一個測試收集這種格式的文件,創建索引,並跑了您發佈與查詢.explain()選項。

正在使用的索引按預期:

> db.test.ensureIndex({"lc":1, "group":1, "indices.text":1, "indices.pos":1}) 
> db.test.find({ lc: "eng", group: "xyz", indices: { $elemMatch: { text: "as", pos: { $gt: 1 } } } }).explain() 
{ 
    "cursor" : "BtreeCursor lc_1_group_1_indices.text_1_indices.pos_1", 
    "isMultiKey" : true, 
    "n" : NumberLong(1), 
    "nscannedObjects" : NumberLong(1), 
    "nscanned" : NumberLong(1), 
    "scanAndOrder" : false, 
    "indexOnly" : false, 
    "nYields" : 0, 
    "nChunkSkips" : NumberLong(0), 
    "millis" : 0, 
    "indexBounds" : { 
     "lc" : [ 
      [ 
       "eng", 
       "eng" 
      ] 
     ], 
     "group" : [ 
      [ 
       "xyz", 
       "xyz" 
      ] 
     ], 
     "indices.text" : [ 
      [ 
       "as", 
       "as" 
      ] 
     ], 
     "indices.pos" : [ 
      [ 
       { 
        "$minElement" : 1 
       }, 
       { 
        "$maxElement" : 1 
       } 
      ] 
     ] 
    }, 
    "server" : "Marcs-MacBook-Pro.local:27017" 
} 

在.explain()功能的文檔可在這裏找到:http://www.mongodb.org/display/DOCS/Explain

.explain()可用於顯示有關信息查詢,包括使用哪個(如果有)索引。

+0

謝謝馬克 - 是的,我的文件看起來像那樣。我從解釋中注意到,'indexOnly'是錯誤的。這並不表示即使字段全部位於索引中,BSON也必須解壓縮和掃描嗎? – 2012-04-18 17:51:03

+0

樂意幫忙! IndexOnly不適用於多鍵索引。這是因爲每個嵌入式文檔在索引中都有自己的條目。整個「索引」數組不存儲在單個索引條目中。因此,即使使用索引,也必須讀取實際的文檔。這可以在「Multikeys」文檔中的「索引中的精確數組匹配」一節中進行解釋:http://www.mongodb.org/display/DOCS/Multikeys – Marc 2012-04-18 18:24:48

+0

我可以理解,如果我查詢'db.test.find ({lc:「eng」,group:「xyz」,「indices.text:」as「,」indices.pos「:{$ gt:1}}})'不需要$ elemMatch它需要掃描對象,但由於elemMatch需要已經在索引條目中的相同子對象,不是嗎? – 2012-04-19 09:04:27