$rename
Renames fields in documents during update operations, removing the old field name and creating a new field with the same value.
Syntax
{ $rename: { <field1>: <newName1>, <field2>: <newName2> } }
Parameters
field
stringrequiredThe current name of the field to be renamed
newName
stringrequiredThe new name for the field
Examples
Rename top-level fields
Rename name field to storeName and location to storeLocation
Query:
db.stores.updateOne({ "_id": "store-001" }, { $rename: { "name": "storeName", "location": "storeLocation" } })
Output:
Renames specified fields while preserving their values
Rename nested fields
Rename nested fields using dot notation
Query:
db.stores.updateOne({ "_id": "store-001" }, { $rename: { "location.lat": "location.latitude", "location.lon": "location.longitude" } })
Output:
Renames nested coordinate fields to more descriptive names