$rename運算子可用來在更新作業期間重新命名檔中的欄位。 它會移除具有舊名稱的欄位,並建立具有指定名稱的新字段,並保留原始值。 此運算子適用於重組文件架構或更正欄位命名慣例。
語法
{
$rename: {
<field1>: <newName1>,
<field2>: <newName2>,
...
}
}
參數
| 參數 | Description |
|---|---|
field |
要重新命名之欄位的目前名稱。 |
newName |
欄位的新名稱。 |
範例
請參考商店集合中的此範例檔。
{
"_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:重新命名最上層欄位
若要將欄位重新命名 name 為 storeName 和 location to storeLocation,請將 $rename 運算子與這兩個欄位搭配使用。
db.stores.updateOne(
{ "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" },
{
$rename: {
"name": "storeName",
"location": "storeLocation"
}
}
)
範例 2:重新命名巢狀欄位
您也可以使用點表示法來重新命名巢狀欄位。
db.stores.updateOne(
{ "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" },
{
$rename: {
"location.lat": "location.latitude",
"location.lon": "location.longitude",
"staff.totalStaff.fullTime": "staff.totalStaff.fullTimeEmployees"
}
}
)
範例 3:大量重新命名作業
您可以使用 重新命名多個檔案的 updateMany()欄位。
db.stores.updateMany(
{},
{
$rename: {
"sales.totalSales": "sales.revenue",
"staff.totalStaff": "staff.employeeCount"
}
}
)
這很重要
如果 中指定的 $rename 欄位不存在,則作業不會影響該欄位。
如果新的功能變數名稱已經存在,作業 $rename 將會覆寫現有的欄位。
$rename運算子無法用來重新命名陣列元素或陣列元素內的欄位。
功能變數名稱不可以是空字串或包含 Null 字元。