$addFields - Amazon DocumentDB

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

$addFields

Amazon DocumentDB 集約パイプラインの $addFieldsステージでは、新しい計算フィールドをドキュメントに追加できます。これは、派生データまたは変換されたデータをドキュメントに追加するのに役立ちます。

パラメータ

  • newField: 追加する新しいフィールドの名前。

  • expression: 新しいフィールドの値に解決される式。

例 (MongoDB シェル)

次の例は、 $addFieldsを使用して、 Inventory.OnHand および フィールドに基づいてインベントリの合計TotalInventoryを計算する新しいInventory.OrderQntyフィールドを追加する方法を示しています。

サンプルドキュメントを作成する

db.example.insertMany([ { "Item": "Spray Paint", "Colors": ["Black", "Red", "Green", "Blue"], "Inventory": { "OnHand": 47, "MinOnHand": 50, "OrderQnty": 36 }, "UnitPrice": 3.99 }, { "Item": "Ruler", "Colors": ["Red", "Green", "Blue", "Clear", "Yellow"], "Inventory": { "OnHand": 47, "MinOnHand": 40 }, "UnitPrice": 0.89 } ]);

クエリの例

db.example.aggregate([ { $addFields: { TotalInventory: { $add: ["$Inventory.OnHand", "$Inventory.OrderQnty"] } } } ])

出力

[ { "_id" : ObjectId("5bedafbcf65ff161707de24f"), "Item" : "Ruler", "Colors" : [ "Red", "Green", "Blue", "Clear", "Yellow" ], "Inventory" : { "OnHand" : 47, "MinOnHand" : 40 }, "UnitPrice" : 0.89, "TotalInventory" : 47 }, { "_id" : ObjectId("5bedafbcf65ff161707de250"), "Item" : "Spray Paint", "Colors" : [ "Black", "Red", "Green", "Blue" ], "Inventory" : { "OnHand" : 47, "MinOnHand" : 50, "OrderQnty" : 36 }, "UnitPrice" : 3.99, "TotalInventory" : 83 } ]

コードの例

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

Node.js
const { MongoClient } = require('mongodb'); const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('example'); const result = await collection.aggregate([ { $addFields: { TotalInventory: { $add: ['$Inventory.OnHand', '$Inventory.OrderQnty'] } } } ]).toArray(); console.log(result); await client.close();
Python
from pymongo import MongoClient 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['example'] result = list(collection.aggregate([ { '$addFields': { 'TotalInventory': { '$add': ['$Inventory.OnHand', '$Inventory.OrderQnty'] } } } ])) print(result) client.close()