View a markdown version of this page

$sum - Amazon DocumentDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

$sum

L'$sumoperatore in Amazon DocumentDB restituisce la somma dell'espressione specificata per ogni documento in un gruppo. È un operatore di accumulazione di gruppo che viene in genere utilizzato nella fase $group di una pipeline di aggregazione per eseguire calcoli di sommatoria.

Parametri

  • expression: L'espressione numerica da sommare. Può essere un percorso di campo, un'espressione o una costante.

Esempio (MongoDB Shell)

L'esempio seguente dimostra l'uso dell'$sumoperatore per calcolare le vendite totali per ciascun prodotto.

Crea documenti di esempio

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

Esempio di interrogazione

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

Output

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

Esempio di utilizzo dell'operatore di finestra (MongoDB Shell)

Nuovo dalla versione 8.0.2.

L'$sumoperatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce la somma dell'espressione specificata per i documenti in ogni finestra. Si specifica l'operatore sotto il output campo e, facoltativamente, si definiscono i confini della finestra con un window documento.

Create documenti di esempio

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

Esempio di interrogazione

L'esempio seguente suddivide i documenti in baseproduct, ordina ogni partizione in base day e restituisce un totale progressivo amount compreso tra l'inizio della partizione e il documento corrente.

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

Output

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

Ogni documento è runningTotal arricchito dalla somma cumulativa contenuta amount nella sua partizione fino al documento corrente incluso.

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo dell'$sumoperatore, scegli la scheda corrispondente alla lingua che desideri utilizzare. Gli esempi seguenti mostrano sia l'utilizzo dell'accumulatore (in$group) che l'utilizzo dell'operatore di finestra (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()