2013-04-12 68 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