$rename演算子は、更新操作中にドキュメント内のフィールドの名前を変更するために使用されます。 古い名前のフィールドが削除され、指定した名前の新しいフィールドが作成され、元の値が保持されます。 この演算子は、ドキュメント スキーマの再構築やフィールドの名前付け規則の修正に役立ちます。
構文
{
$rename: {
<field1>: <newName1>,
<field2>: <newName2>,
...
}
}
パラメーター
| パラメーター | Description |
|---|---|
field |
名前を変更するフィールドの現在の名前。 |
newName |
フィールドの新しい名前。 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_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に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"
}
}
)
Important
$renameで指定されたフィールドが存在しない場合、操作はそのフィールドに影響しません。
新しいフィールド名が既に存在する場合、 $rename 操作によって既存のフィールドが上書きされます。
$rename演算子を使用して、配列要素または配列要素内のフィールドの名前を変更することはできません。
フィールド名を空の文字列にしたり、null 文字を含めることはできません。