$set - Amazon DocumentDB

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

$set

バージョン 8.0 の新機能

Elastic クラスターではサポートされていません。

Amazon DocumentDB の$set集約ステージでは、集約パイプライン中にドキュメントに新しいフィールドを追加したり、既存のフィールド値を更新したりできます。

パラメータ

  • expression: 評価する式。これは、フィールド参照や算術演算など、任意の有効な集計式にすることができます。

例 (MongoDB シェル)

次の例は、$set集計ステージを使用して、 quantityフィールドに priceフィールドを乗算して合計を計算する方法を示しています。

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

db.inventory.insertMany([ { item: "pencil", quantity: 100, price: 0.24}, { item: "pen", quantity: 204, price: 1.78 } ]);

集約の例

db.inventory.aggregate([ { $set: { total: { $multiply: ["$quantity", "$price"] } } } ])

出力

[ { _id: ObjectId('69248951d66dcae121d2950d'), item: 'pencil', quantity: 100, price: 0.24, total: 24 }, { _id: ObjectId('69248951d66dcae121d2950e'), item: 'pen', quantity: 204, price: 1.78, total: 363.12 } ]

コードの例

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

Node.js
const { MongoClient } = require('mongodb'); async function example() { 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 inventory = db.collection('inventory'); const result = await inventory.aggregate([ { $set: { total: { $multiply: ["$quantity", "$price"] } } } ]).toArray(); console.log(result); client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] inventory = db['inventory'] result = list(inventory.aggregate([ { "$set": { "total": { "$multiply": ["$quantity", "$price"] } } } ])) print(result) client.close() example()