How to Use $rename in MongoDB: Syntax and Examples
In MongoDB, use the
$rename update operator to change the name of a field in a document. It takes an object where keys are current field names and values are the new field names, applied during an update operation.Syntax
The $rename operator is used inside an update command to rename fields in documents. It requires an object where each key is the current field name and the corresponding value is the new field name.
- updateOne(filter, update): Updates a single document matching the filter.
- updateMany(filter, update): Updates multiple documents matching the filter.
$rename: { oldFieldName: newFieldName }: Specifies the field rename mapping.
mongodb
db.collection.updateOne(
{ <filter> },
{ $rename: { "oldField": "newField" } }
)Example
This example renames the field username to user_name in a single document where _id is 1.
mongodb
db.users.insertOne({ _id: 1, username: "alice", age: 25 })
db.users.updateOne(
{ _id: 1 },
{ $rename: { "username": "user_name" } }
)
db.users.find({ _id: 1 })Output
{ "_id" : 1, "user_name" : "alice", "age" : 25 }
Common Pitfalls
Common mistakes when using $rename include:
- Trying to rename a field that does not exist (no error, but no change).
- Renaming to a field name that already exists (the existing field will be overwritten).
- Using dot notation incorrectly when renaming nested fields.
Always verify the field names and test on sample data before applying to production.
mongodb
/* Wrong: renaming non-existent field (no effect) */ db.users.updateOne( { _id: 1 }, { $rename: { "nonexistent": "newField" } } ) /* Right: renaming existing field */ db.users.updateOne( { _id: 1 }, { $rename: { "age": "user_age" } } )
Quick Reference
| Usage | Description |
|---|---|
| $rename: { oldField: newField } | Rename a field from oldField to newField |
| updateOne(filter, update) | Update a single document matching filter |
| updateMany(filter, update) | Update multiple documents matching filter |
| Field must exist | Only existing fields can be renamed |
| Overwrites existing fields | New field name overwrites if it exists |
Key Takeaways
Use $rename inside update operations to rename fields in MongoDB documents.
The operator takes an object mapping old field names to new field names.
Renaming a non-existent field does nothing and causes no error.
Renaming to an existing field name overwrites that field's value.
Test renames carefully to avoid data loss or unexpected overwrites.