

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

Amazon DocumentDB 中的`$reduce`聚合运算符用于将包含两个参数的函数累积应用于数组的元素，以将数组缩减为单个值。对于在聚合管道中对数组数据执行复杂的计算或转换，此运算符特别有用。

**参数**
+ `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()
```

------