$set - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$set

8.0 版的新功能

Elastic 叢集不支援。

Amazon DocumentDB $set 中的彙總階段可讓您在彙總管道期間新增欄位或更新文件中現有的欄位值。

參數

  • expression:要評估的表達式。這可以是任何有效的彙總表達式,包括欄位參考和算術操作。

範例 (MongoDB Shell)

下列範例示範使用$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()