本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$set
8.0 版的新增内容
弹性集群不支持。
Amazon DocumentDB 中的$set聚合阶段允许您在聚合管道期间添加新字段或更新文档中的现有字段值。
参数
示例(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()