$reduce - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$reduce

Amazon DocumentDB $reduce 中的彙總運算子用於將兩個引數的函數累加到陣列的元素,以將陣列減少為單一值。此運算子特別適用於對彙總管道中的陣列資料執行複雜的計算或轉換。

參數

  • input:要減少的陣列。

  • initialValue:要在縮減操作中使用的初始值。

  • in:要在input陣列的每個元素上評估的表達式。此表達式應該會傳回值,用於下一次的縮減反覆運算。

範例 (MongoDB Shell)

下列範例示範如何使用 $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()