Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$set
Amazon DocumentDB 中的$set运算符用于更新文档中指定字段的值。此运算符允许您在文档中添加新字段或修改现有字段。它是 MongoDB Java 驱动程序中的基本更新操作符,与亚马逊 DocumentDB 兼容。
参数
-
field:要更新的字段。
-
value:该字段的新值。
示例(MongoDB 外壳)
以下示例演示如何使用$set运算符更新文档中的Item字段。
创建示例文档
db.example.insert([
{
"Item": "Pen",
"Colors": ["Red", "Green", "Blue", "Black"],
"Inventory": {
"OnHand": 244,
"MinOnHand": 72
}
},
{
"Item": "Poster Paint",
"Colors": ["Red", "Green", "Blue", "White"],
"Inventory": {
"OnHand": 120,
"MinOnHand": 36
}
}
])
查询示例
db.example.update(
{ "Item": "Pen" },
{ $set: { "Item": "Gel Pen" } }
)
输出
{
"Item": "Gel Pen",
"Colors": ["Red", "Green", "Blue", "Black"],
"Inventory": {
"OnHand": 244,
"MinOnHand": 72
}
}
代码示例
要查看使用该$set命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function updateDocument() {
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');
await collection.updateOne(
{ "Item": "Pen" },
{ $set: { "Item": "Gel Pen" } }
);
const updatedDocument = await collection.findOne({ "Item": "Gel Pen" });
console.log(updatedDocument);
await client.close();
}
updateDocument();
- Python
-
from pymongo import MongoClient
def update_document():
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
collection.update_one(
{"Item": "Pen"},
{"$set": {"Item": "Gel Pen"}}
)
updated_document = collection.find_one({"Item": "Gel Pen"})
print(updated_document)
client.close()
update_document()