$rename (Rename Field)
Last updated: 2026-10-09
$rename (Rename Field)
$rename renames a field. `{ $rename: { 'oldName': 'newName' } }`, with dotted paths for nested fields. If the new name already exists, the old value overwrites it; otherwise the field is created. $rename does not rename fields inside array elements, and moving a nested field does not create intermediate documents.
| Category | Update Field |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $rename: { <old field name>: <new field name> } }
⚙️ Parameters
| old field name | The source field name. |
|---|---|
| new field name | The target field name; dotted paths allowed. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $rename: rename username to handle
// Ignored if the field is missing
db.users.updateOne(
{ _id: 1 },
{ $rename: { username: 'handle' } }
)
// Nested field rename
db.users.updateOne(
{ _id: 1 },
{ $rename: { 'profile.city': 'profile.cityName' } }
)
Output:
// username becomes handle; profile.city becomes profile.cityName
📌 Notes
- An existing new-name field is overwritten by the old value
- Fields inside array elements are not renamed
- Silently ignored when the source field is missing
🏷️ Related Tags
💡 Related Cases
Hands-On: CRUD for a Blog Comment System
Document Update: A Detailed Explanation of `updateOne` and `updateMany`
📚 Related Tutorials
❓ FAQ
QCan $rename rename nested fields?
AYes, via dotted paths like 'profile.city'.
QWhat happens if the new field name already exists?
AThe old value overwrites the existing new field.
QDoes $rename handle fields inside arrays?
ANo, fields inside array elements need per-element updates.