View a markdown version of this page

$sum - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$sum

$sumOperator di Amazon DocumentDB mengembalikan jumlah ekspresi yang ditentukan untuk setiap dokumen dalam grup. Ini adalah operator akumulator grup yang biasanya digunakan dalam tahap $group dari pipa agregasi untuk melakukan perhitungan penjumlahan.

Parameter

  • expression: Ekspresi numerik untuk menjumlahkan. Ini bisa berupa jalur bidang, ekspresi, atau konstanta.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan penggunaan $sum operator untuk menghitung total penjualan untuk setiap produk.

Buat dokumen sampel

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 } ]);

Contoh kueri

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

Keluaran

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

Contoh penggunaan operator jendela (MongoDB Shell)

Baru dari versi 8.0.2.

$sumOperator juga dapat digunakan sebagai operator jendela di pang $setWindowFields gung. Dalam konteks ini, ia mengembalikan jumlah ekspresi yang ditentukan untuk dokumen di setiap jendela. Anda menentukan operator di bawah output bidang, dan secara opsional menentukan batas jendela dengan window dokumen.

Buat dokumen sampel

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 } ]);

Contoh kueri

Contoh berikut mempartisi dokumen berdasarkanproduct, mengurutkan setiap partisi berdasarkanday, dan mengembalikan total berjalan amount dari awal partisi melalui dokumen saat ini.

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

Keluaran

[ { "_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 } ]

Setiap dokumen ditambah denganrunningTotal, jumlah kumulatif dari amount dalam partisinya hingga dan termasuk dokumen saat ini.

Contoh kode

Untuk melihat contoh kode untuk menggunakan $sum operator, pilih tab untuk bahasa yang ingin Anda gunakan. Contoh berikut menunjukkan penggunaan akumulator (in$group) dan penggunaan operator jendela (in$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()