翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$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 シェル)
バージョン 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()