$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 jumlah. Ini bisa berupa jalur lapangan, 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 kode

Untuk melihat contoh kode untuk menggunakan $sum perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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()