2013-04-12 67 views
0

這是產品集合中文檔的示例。MongoDB:選擇特定的子文檔

object(MongoId)#8 (1) { 
    ["$id"]=> 
    string(24) "5165b2c8ac951ab812000001" 
} 
int(0) 
array(7) { 
    [0]=> 
    array(2) { 
    ["sValue"]=> 
    string(10) "1223828372" 
    ["iPosX"]=> 
    int(0) 
    } 
    [1]=> 
    array(2) { 
    ["sValue"]=> 
    string(12) "Epson EB-S11" 
    ["iPosX"]=> 
    int(1) 
    } 
    [2]=> 
    array(2) { 
    ["sValue"]=> 
    string(6) "Beamer" 
    ["iPosX"]=> 
    int(2) 
    } 
    [3]=> 
    array(2) { 
    ["sValue"]=> 
    string(48) "TV>>Beamer & Projektoren|Epson EB-S11-1300742000" 
    ["iPosX"]=> 
    int(3) 
    } 
    [4]=> 
    array(2) { 
    ["sValue"]=> 
    string(6) "398.00" 
    ["iPosX"]=> 
    int(4) 
    } 
    [5]=> 
    array(2) { 
    ["sValue"]=> 
    string(85) "http://www.myshop.com/product-1223828372.html" 
    ["iPosX"]=> 
    int(5) 
    } 
    [6]=> 
    array(2) { 
    ["sValue"]=> 
    string(5) "Epson" 
    ["iPosX"]=> 
    int(6) 
    } 
} 

我想選擇此集合中的產品,但不是所有的子文檔。例如:我只想從本文檔中獲取iPosX爲1,2或4的子文檔。

具體地說:我需要這個產品加在iPosX字段是1,2或4

我怎麼可以這樣子文檔的所有信息?

在此先感謝。 最大

回答

1

你最好的辦法是在MongoDB中使用Aggregation Framework 2.2+:

db.products.aggregate(
    // Optional: could include a $match to limit the matching documents 

    // Create a stream of documents from the products array 
    { $unwind: "$products" }, 

    // Filter the matching products 
    { $match: { 
     "products.iPosX": { $in: [1,2,4] } 
    }}, 

    // Reshape output so matched products are at top level of results 
    { $project: { 
     _id: 0, 
     sValue: "$products.sValue", 
     iPosX: "$products.iPosX", 
    }} 
) 

輸出示例:

{ 
    "result" : [ 
     { 
      "sValue" : "Epson EB-S11", 
      "iPosX" : 1 
     }, 
     { 
      "sValue" : "Beamer", 
      "iPosX" : 2 
     }, 
     { 
      "sValue" : "398.00", 
      "iPosX" : 4 
     } 
    ], 
    "ok" : 1 
} 
+0

您可能還需要投票/觀看功能要求[SERVER-6612 ](https://jira.mongodb.org/browse/SERVER-6612)在MongoDB Jira問題跟蹤器中。這個功能建議是支持在普通的find()查詢中使用投影說明符來投影多個數組值(例如,類似於'$ elemMatch',但返回所有匹配元素而不是僅找到第一個匹配元素)。 – Stennie