本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$set
Amazon DocumentDB 中的$set運算子用於更新文件中指定欄位的值。此運算子可讓您新增欄位或修改文件中現有的欄位。它是 MongoDB Java 驅動程式中的基本更新運算子,與 Amazon DocumentDB 相容。
參數
-
field:要更新的欄位。
-
value: 欄位的新值。
範例 (MongoDB Shell)
下列範例示範如何使用 $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()