View a markdown version of this page

$sum - Amazon DocumentDB

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

$sum

Der $sum Operator in Amazon DocumentDB gibt die Summe des angegebenen Ausdrucks für jedes Dokument in einer Gruppe zurück. Es handelt sich um einen Operator für Gruppenakkumulatoren, der typischerweise in der $group-Phase einer Aggregationspipeline verwendet wird, um Summenberechnungen durchzuführen.

Parameter

  • expression: Der zu summierende numerische Ausdruck. Dies kann ein Feldpfad, ein Ausdruck oder eine Konstante sein.

Beispiel (MongoDB Shell)

Das folgende Beispiel zeigt die Verwendung des $sum Operators zur Berechnung des Gesamtumsatzes für jedes Produkt.

Erstellen Sie Beispieldokumente

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

Beispiel für eine Abfrage

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

Ausgabe

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

Beispiel für die Verwendung von Fensteroperatoren (MongoDB Shell)

Neu ab Version 8.0.2.

Der $sum Operator kann auch als Fensterbediener auf der $setWindowFields Bühne verwendet werden. In diesem Zusammenhang gibt es die Summe des angegebenen Ausdrucks für die Dokumente in jedem Fenster zurück. Sie geben den Operator unter dem output Feld an und definieren optional die Fenstergrenzen mit einem window Dokument.

Erstellen Sie Beispieldokumente

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

Beispiel für eine Abfrage

Das folgende Beispiel partitioniert die Dokumente nachproduct, sortiert jede Partition nach day und gibt eine laufende Summe amount vom Anfang der Partition bis zum aktuellen Dokument zurück.

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

Ausgabe

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

Jedes Dokument wird um die kumulative Summe amount innerhalb der Partition bis einschließlich des aktuellen Dokuments erweitert. runningTotal

Codebeispiele

Um ein Codebeispiel für die Verwendung des $sum Operators anzuzeigen, wählen Sie die Registerkarte für die Sprache, die Sie verwenden möchten. Die folgenden Beispiele zeigen sowohl die Verwendung des Akkumulators (in$group) als auch die Verwendung von Fensteroperatoren (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()