Open In App

MongoDB - Rename Operator ($rename)

Last Updated : 29 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB $rename operator is a powerful tool for for efficiently renaming fields within documents. This operator ensures data consistency and helps developers maintain a clear and organized schema, especially when working with large collections. Whether you’re dealing with nested documents, arrays, or simple fields, the $rename operator simplifies field name changes without disrupting the document's structure.

In this article, we will explain everything you need to know about MongoDB’s $rename operator with detailed examples.

What is the MongoDB $rename Operator?

The MongoDB $rename operator allows you to rename fields in your documents, including fields within embedded/nested documents and arrays. This operator is a powerful tool when you want to reorganize your database schema or standardize field names without deleting or replacing data. This operator is used to update the names of the fields with new names. The new name of the field should be different from the existing name of the field.

The $rename operation works by performing the following:

  1. Unset the old field: The operator logically removes the old field name.
  2. Set the new field: It then creates a new field with the new name.

The new field name must differ from the existing one. If a field with the new name already exists, it will be removed and replaced by the renamed field.

Key Features of the MongoDB $rename Operator

  • Renaming simple fields: You can rename straightforward fields in a document.
  • Handling nested fields: It supports renaming fields within embedded documents using dot notation.
  • Works with arrays: You can rename fields within array elements too.
  • No operation on missing fields: If the field you want to rename does not exist, no operation occurs.
  • Multiple field renaming: The $rename operator can rename multiple fields in a single update.

Syntax: 

{ $rename: { <oldField>: <newField>, <oldField2>: <newField2>, ... } }

Key Terms

  • <oldField>: The current name of the field you want to rename.
  • <newField>: The new name for the field.
  • The new name must be different from the old name.
  • For embedded or nested documents, we can use dot notation to refer to the field within the nested structure.

Examples of MongoDB $rename

Let’s look at practical examples of how to use the $rename operator in MongoDB, using an Employee collection as a sample.

  • Database: GeeksforGeeks 
  • Collection: Employee 
  • Document: three documents that contain the details of the employees in the form of field-value pairs.

Example 1: Rename a Single Field

In this example, we are renaming the name of experienceYear field to experience in the employee’s document whose first name is "Amu"

Query:

db.Employee.update(
{ "name.first": "Amu" },
{ $rename: { "experienceYear": "experience" } }
)

Output:

Explanation: The experienceYear field is renamed to experience in the employee document where the first name is "Amu."

Example 2: Renaming a multiple field

In this example, we are renaming the name of the department field to unit in all the documents present in the Employee collection

Query:

db.Employee.updateMany(
{},
{ $rename: { "department": "unit" } }
)

Output:

Explanation: The department field is renamed to unit for all employees in the collection.

Example 3: Rename a Field in an Embedded Document

In this example, we are renaming the name of personalDetails.contactInfo to personalDetails.phoneNumber field in an embedded/nested document of the employee whose name is "Sumit". 

Query:

db.Employee.update(
{ "name.first": "Sumit" },
{ $rename: { "personalDetails.contactInfo": "personalDetails.phoneNumber" } }
)

Output:

rename-example-3

Explanation: The field contactInfo inside the personalDetails embedded document is renamed to phoneNumber for the employee named "Sumit."

Example 4: Renaming a Non-Existent Field

If a field does not exist in the document, the $rename operation will not perform any action. However, we can add a field first and then rename it. Here’s how you can rename a middle name to middleName:

Query:

db.Employee.updateMany(
{ "name.middle": { $exists: false } },
{ $set: { "name.middle": "" } }
);
db.Employee.updateMany(
{},
{ $rename: { "name.middle": "name.middleName" } }
)

Output:

[
{
"_id": ObjectId("5e9823b792e6dfa3fc48ddda"),
"name": {
"first": "Om",
"last": "Goyal",
"middleName": ""
},
"personalDetails": {
"age": 23,
"contactInfo": 222773330
},
"department": "Development",
"salary": 30000,
"experienceYear": 3,
"points": [1, 2, 41],
"joiningDate": ISODate("2020-04-16T09:26:23.669Z")
},
{
"_id": ObjectId("5e9823b792e6dfa3fc48dddb"),
"name": {
"first": "Sumit",
"last": "Singh",
"middleName": ""
},
"personalDetails": {
"age": 24,
"contactInfo": 222993330
},
"department": "HR",
"salary": 35000,
"experienceYear": 2,
"points": [5, 7],
"joiningDate": ISODate("2020-04-16T09:57:20.343Z")
},
{
"_id": ObjectId("5e9823b792e6dfa3fc48dddc"),
"name": {
"first": "Amu",
"last": "Goyal",
"middleName": ""
},
"personalDetails": {
"age": 24,
"contactInfo": 228833330
},
"department": "HR",
"salary": 35000,
"experienceYear": 1,
"points": [7, 6],
"joiningDate": ISODate("2020-04-16T10:12:34.116Z")
}
]

Explanation

  • First, the name.middle field is added with an empty string if it doesn’t exist.
  • Then, the field is renamed to name.middleName.

When to Use MongoDB $rename Operator?

  • Schema evolution: When you need to change the name of a field during schema migration or when adapting to new application requirements.
  • Field standardization: When renaming fields to standardize naming conventions across your collection.
  • Refactoring database: If you're restructuring your database to improve data consistency or query efficiency.

Conclusion

The $rename operator in MongoDB is a versatile and powerful tool for managing your data schema. It allows for seamless renaming of fields across simple documents, nested structures, and arrays. By using this operator, you can ensure that your MongoDB collection remains organized and flexible, especially as your application evolves. With its ability to handle both embedded documents and arrays, the $rename operator helps maintain the integrity of your data while allowing you to adapt to new field names without losing information.


Next Article

Similar Reads