本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$reduce
Amazon DocumentDB 中的$reduce聚合运算符用于将包含两个参数的函数累积应用于数组的元素,以将数组缩减为单个值。对于在聚合管道中对数组数据执行复杂的计算或转换,此运算符特别有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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。结果是数组中所有元素的总和。
代码示例
要查看使用该$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()