0
0
MongodbHow-ToBeginner · 3 min read

How to Use $rename Operator in MongoDB: Syntax and Examples

In MongoDB, the $rename operator is used in an update command to rename a field in a document. You specify the current field name as the key and the new field name as the value inside $rename. This changes the field name without altering the field's value.
📐

Syntax

The $rename operator takes an object where each key is the current field name and the corresponding value is the new field name you want to rename it to.

It is used inside an update operation like this:

  • filter: Selects the documents to update.
  • update: Contains the $rename operator with field mappings.
mongodb
db.collection.updateOne(
  { <filter> },
  { $rename: { "oldFieldName": "newFieldName" } }
)
💻

Example

This example renames the field username to user_name in a document where _id is 1.

mongodb
db.users.insertOne({ _id: 1, username: "alice", age: 25 })

// Rename 'username' to 'user_name'
db.users.updateOne(
  { _id: 1 },
  { $rename: { "username": "user_name" } }
)

// Verify the change
db.users.find({ _id: 1 }).pretty()
Output
{ "_id" : 1, "user_name" : "alice", "age" : 25 }
⚠️

Common Pitfalls

  • Trying to rename a field to a name that already exists in the document will cause an error.
  • Using $rename on fields that do not exist will not cause an error but will have no effect.
  • Remember that $rename only changes field names, not values.
mongodb
/* Wrong: Renaming to an existing field name causes error */
db.users.updateOne(
  { _id: 1 },
  { $rename: { "age": "user_name" } }
)

/* Right: Rename to a new field name */
db.users.updateOne(
  { _id: 1 },
  { $rename: { "age": "user_age" } }
)
📊

Quick Reference

AspectDescription
Operator$rename
PurposeRename fields in documents
UsageInside update commands
Syntax{ $rename: { "oldField": "newField" } }
EffectChanges field name, keeps value unchanged
Error CasesRenaming to existing field name causes error

Key Takeaways

Use $rename inside update commands to rename document fields.
Specify current field names as keys and new names as values in $rename.
Renaming to an existing field name causes an error; avoid name conflicts.
If the field to rename does not exist, $rename does nothing but does not error.
$rename changes only field names, not their values.