

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# \$1reduce
<a name="reduce"></a>

Amazon DocumentDB の`$reduce`集計演算子は、配列の要素に 2 つの引数の関数を累積的に適用して、配列を 1 つの値に減らすために使用されます。この演算子は、集計パイプライン内の配列データに対して複雑な計算または変換を実行する場合に特に便利です。

**パラメータ**
+ `input`: 削減する配列。
+ `initialValue`: 削減オペレーションで使用される初期値。
+ `in`: `input`配列の各要素で評価される式。この式は、次のリダクションの反復で使用される値を返す必要があります。

## 例 (MongoDB シェル)
<a name="reduce-examples"></a>

次の例は、 `$reduce`演算子を使用して配列内のすべての要素の合計を計算する方法を示しています。

**サンプルドキュメントを作成する**

```
db.orders.insertMany([
  { "_id": 1, "items": [1, 2, 3, 4, 5] },
  { "_id": 2, "items": [10, 20, 30] },
  { "_id": 3, "items": [5, 15, 25, 35] },
  { "_id": 4, "items": [100, 200] }
])
```

**クエリの例**

```
db.orders.aggregate([
  {
    $project: {
      total: {
        $reduce: {
          input: "$items",
          initialValue: 0,
          in: { $add: ["$$value", "$$this"] }
        }
      }
    }
  }
])
```

**出力**

```
[
  { "_id": 1, "total": 15 },
  { "_id": 2, "total": 60 },
  { "_id": 3, "total": 80 },
  { "_id": 4, "total": 300 }
]
```

`$reduce` 演算子は`items`配列を繰り返し、各要素を 0 `initialValue`の に追加します。結果は、配列内のすべての要素の合計です。

## コードの例
<a name="reduce-code"></a>

`$reduce` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

Node.js アプリケーションで `$reduce`演算子を使用する例を次に示します。

```
const { MongoClient } = require("mongodb");

async function main() {
  const client = await MongoClient.connect("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
  const db = client.db("test");
  const orders = db.collection("orders");

  const result = await orders.aggregate([
    {
      $project: {
        total: {
          $reduce: {
            input: "$items",
            initialValue: 0,
            in: { $add: ["$$value", "$$this"] }
          }
        }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

Python アプリケーションで `$reduce`演算子を使用する例を次に示します。

```
from pymongo import MongoClient

def main():
    client = MongoClient("mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false")
    db = client["test"]
    orders = db["orders"]

    result = list(orders.aggregate([
        {
            "$project": {
                "total": {
                    "$reduce": {
                        "input": "$items",
                        "initialValue": 0,
                        "in": { "$add": ["$$value", "$$this"] }
                    }
                }
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == "__main__":
    main()
```

------