如果現有欄位不存在,運算符 $set 會更新現有的欄位,或建立具有指定值的新欄位。 列出的一或多個欄位已經更新或建立。 點表示法可用來更新或建立巢狀物件。
語法
{
$set: {
newField: <expression>
}
}
參數
| 參數 | Description |
|---|---|
newField |
要更新或建立的欄位名稱 |
expression |
定義新或更新欄位值的表達式 |
範例
請參考商店集合中的此範例檔。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
範例 1 - 更新現有的欄位
db.stores.updateOne({
_id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0"
},
{
$set: {
name: "Lakeshore Retail"
}
})
範例 2 - 更新巢狀物件中的現有欄位
db.stores.updateOne({
_id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0"
},
{
$set: {
"staff.totalStaff.partTime": 9
}
})
範例 3 - 建立不存在的新欄位
使用存放區舊名稱建立名為 「formerName」 的新欄位。
db.stores.updateOne({
_id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0"
},
{
$set: {
formerName: "Tailwind Traders | Drone Shoppe - New Theodora"
}
})
範例 4 - 在巢狀物件中建立新欄位
在巢狀 totalStaff 物件內建立新的欄位,以指定暫存人員成員的計數。
db.stores.updateOne({
_id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0"
},
{
$set: {
"staff.totalStaff.temporary": 3
}
})
範例 5 - 更新多個字段
db.stores.updateOne({
_id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0"
},
{
$set: {
"staff.totalStaff.partTime": 9,
"sales.totalSales": 3611
}
})