기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$sum
Amazon DocumentDB의 $sum 연산자는 그룹의 각 문서에 대해 지정된 표현식의 합계를 반환합니다. 집계 파이프라인의 $group 단계에서 일반적으로 합계 계산을 수행하는 데 사용되는 그룹 누적기 연산자입니다.
파라미터
예제(MongoDB 쉘)
다음 예제에서는 $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 }
]
각 문서는 현재 문서까지 파티션 amount 내의 누적 합계runningTotal인 로 보강됩니다.
코드 예제
$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()