View a markdown version of this page

$sum - Amazon DocumentDB

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

$sum

Amazon DocumentDB 中的$sum运算符返回组中每个文档的指定表达式的总和。它是一个分组累加器运算符,通常在聚合管道的 $group 阶段用于执行求和计算。

参数

  • expression:求和的数字表达式。这可以是字段路径、表达式或常量。

示例(MongoDB Shell)

以下示例演示如何使用运$sum算符计算每种产品的总销售额。

创建示例文档

db.sales.insertMany([ { product: "abc", price: 10, quantity: 2 }, { product: "abc", price: 10, quantity: 3 }, { product: "xyz", price: 20, quantity: 1 }, { product: "xyz", price: 20, quantity: 5 } ]);

查询示例

db.sales.aggregate([ { $group: { _id: "$product", totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } } }} ]);

输出

[ { "_id": "abc", "totalSales": 50 }, { "_id": "xyz", "totalSales": 120 } ]

窗口运算符用法示例(MongoDB Shell)

8.0.2 版中的新内容。

该$sum操作员还可以在$setWindowFields舞台中用作窗口操作员。在此上下文中,它返回每个窗口中文档的指定表达式的总和。您可以在output字段下指定运算符,也可以选择使用window文档定义窗口边界。

创建示例文档

db.dailySales.insertMany([ { _id: 1, product: "abc", day: 1, amount: 10 }, { _id: 2, product: "abc", day: 2, amount: 20 }, { _id: 3, product: "abc", day: 3, amount: 15 }, { _id: 4, product: "xyz", day: 1, amount: 30 }, { _id: 5, product: "xyz", day: 2, amount: 25 } ]);

查询示例

以下示例按对文档进行分区product,按分区排序day,并返回amount从分区开始到当前文档的运行总数。

db.dailySales.aggregate([ { $setWindowFields: { partitionBy: "$product", sortBy: { day: 1 }, output: { runningTotal: { $sum: "$amount", window: { documents: ["unbounded", "current"] } } } } } ]);

输出

[ { "_id": 1, "product": "abc", "day": 1, "amount": 10, "runningTotal": 10 }, { "_id": 2, "product": "abc", "day": 2, "amount": 20, "runningTotal": 30 }, { "_id": 3, "product": "abc", "day": 3, "amount": 15, "runningTotal": 45 }, { "_id": 4, "product": "xyz", "day": 1, "amount": 30, "runningTotal": 30 }, { "_id": 5, "product": "xyz", "day": 2, "amount": 25, "runningTotal": 55 } ]

每个文档都添加了runningTotal其分区amount内直到包括当前文档在内的累积总和。

代码示例

要查看使用$sum运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示了累加器的用法(输入$group)和窗口运算符的用法(输入$setWindowFields):

Node.js
const { MongoClient } = require('mongodb'); async function example() { const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('test'); // Accumulator usage: sum per group const sales = db.collection('sales'); await sales.insertMany([ { product: "abc", price: 10, quantity: 2 }, { product: "abc", price: 10, quantity: 3 }, { product: "xyz", price: 20, quantity: 1 }, { product: "xyz", price: 20, quantity: 5 } ]); const accumulatorResult = await sales.aggregate([ { $group: { _id: "$product", totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } } }} ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: running total within each partition const dailySales = db.collection('dailySales'); await dailySales.insertMany([ { _id: 1, product: "abc", day: 1, amount: 10 }, { _id: 2, product: "abc", day: 2, amount: 20 }, { _id: 3, product: "abc", day: 3, amount: 15 }, { _id: 4, product: "xyz", day: 1, amount: 30 }, { _id: 5, product: "xyz", day: 2, amount: 25 } ]); const windowResult = await dailySales.aggregate([ { $setWindowFields: { partitionBy: "$product", sortBy: { day: 1 }, output: { runningTotal: { $sum: "$amount", window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); } catch (error) { console.error('Error:', error); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from pprint import pprint def example(): client = None try: client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client.test # Accumulator usage: sum per group sales = db.sales sales.insert_many([ { 'product': 'abc', 'price': 10, 'quantity': 2 }, { 'product': 'abc', 'price': 10, 'quantity': 3 }, { 'product': 'xyz', 'price': 20, 'quantity': 1 }, { 'product': 'xyz', 'price': 20, 'quantity': 5 } ]) accumulator_result = list(sales.aggregate([ { '$group': { '_id': '$product', 'totalSales': { '$sum': { '$multiply': [ '$price', '$quantity' ] } } }} ])) pprint(accumulator_result) # Window operator usage: running total within each partition daily_sales = db.dailySales daily_sales.insert_many([ { '_id': 1, 'product': 'abc', 'day': 1, 'amount': 10 }, { '_id': 2, 'product': 'abc', 'day': 2, 'amount': 20 }, { '_id': 3, 'product': 'abc', 'day': 3, 'amount': 15 }, { '_id': 4, 'product': 'xyz', 'day': 1, 'amount': 30 }, { '_id': 5, 'product': 'xyz', 'day': 2, 'amount': 25 } ]) window_result = list(daily_sales.aggregate([ { '$setWindowFields': { 'partitionBy': '$product', 'sortBy': { 'day': 1 }, 'output': { 'runningTotal': { '$sum': '$amount', 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) pprint(window_result) except Exception as e: print(f"An error occurred: {e}") finally: if client: client.close() example()