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.
- $rename operator logically first performs an $unset operation on both the old name and the new name and then performs an $set operation with the new name.
- If the document contains the field with the new name, then this operator will remove that field and renames the specified field to the new name.
- This operator can also work with embedded/nested documents or arrays. In embedded/nested documents, this operator can rename the specified field as well as move the fields in and out of the embedded documents
- You can use this operator in methods like update(), findAndModify(), etc., according to your requirements.
- If the specified field for renaming is not available, then this operator will do nothing.
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: w3wiki
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.
Python3
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.
Python3
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.
Python3
db.Employee.update({"name.first": "Sumit"}, {$rename: {"personalDetails.contactInfo":"personalDetails.phoneNumber"}}) |
Contact Us