Open In App

MongoDB – Rename Operator ($rename)

MongoDB provides different types of field update operators to update the values of the fields of the documents and $rename operator is one of them. 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.

Syntax: 



{$rename: {<field1>:<newName1>, <field2>:<newName2>, ... } }

Here, newName is the new name and it must be different from the existing name of the field. To specify field in embedded/nested documents with the help of dot notation. 

In the following examples, we are working with:



Database: GeeksforGeeks 

Collection: Employee 

Document: three documents that contain the details of the employees in the form of field-value pairs.

Renaming a field in a single document:

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




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

Renaming a field in multiple documents:

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




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

Renaming a field in nested/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. 




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


Article Tags :