本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$sum
Amazon DocumentDB 中的$sum運算子會傳回群組中每個文件的指定表達式總和。這是一個群組累積器運算子,通常用於彙總管道的 $group 階段,以執行總和計算。
參數
範例 (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()