$sum - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$sum

Amazon DocumentDB の $sum演算子は、グループ内のドキュメントごとに指定された式の合計を返します。これは、集計パイプラインの $group ステージで集計計算を実行するために通常使用されるグループアキュムレータ演算子です。

パラメータ

  • expression: 合計する数値式。これは、フィールドパス、式、または定数です。

例 (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 } ]

コードの例

$sum コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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