기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$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 }
]
코드 예제
$sum 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.
- 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');
const collection = db.collection('sales');
const result = await collection.aggregate([
{ $group: {
_id: "$product",
totalSales: { $sum: { $multiply: [ "$price", "$quantity" ] } }
}}
]).toArray();
console.log(result);
} 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
collection = db.sales
result = list(collection.aggregate([
{ '$group': {
'_id': '$product',
'totalSales': { '$sum': { '$multiply': [ '$price', '$quantity' ] } }
}}
]))
pprint(result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()