0

これは製品コレクション内のドキュメントの例です。

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 であるサブドキュメントが必要です。

これどうやってするの?

前もって感謝します。マックス

4

1 に答える 1

1

最善の方法は、MongoDB 2.2 以降でAggregation Frameworkを使用することです。

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
}
于 2013-04-13T12:19:14.360 に答える