The Wayback Machine - https://web.archive.org/web/20240927175531/https://www.geeksforgeeks.org/mongodb-rename-operator-rename/
Open In App

MongoDB – Rename Operator ($rename)

Last Updated : 21 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

MongoDB $rename operator is a powerful tool for updating field names within documents which ensures data consistency and structure.

This operator allows developers to rename fields in a MongoDB collection, including those nested within documents or arrays. In this article, We will learn about the MongoDB $rename by understanding various examples in detail.

MongoDB $rename

MongoDB provides different types of field update operators to update the values of the fields of the documents and the $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 rename 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
  • We can use this operator in methods like update(), findAndModify() etc. according to our 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. 

Examples of MongoDB $rename

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.

Output:

Example 1: Rename a Field

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({&quot;name.first&quot;: &quot;Amu&quot;}, 
{$rename: {&quot;experienceYear&quot;:&quot;experience&quot;}})

Output:

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. 

db.Employee.updateMany({}, {$rename: {&quot;department&quot;:&quot;unit&quot;}})

Output:

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. 

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

Output:

rename-example-3

Example 4: Rename a Field That Does Not Exist

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

  1. Step 1: Ensures all documents have a name.middle field with a default empty string if it didn’t already exist.
  2. Step 2: Renames the name.middle field to name.middleName in all documents.

This output reflects the updated collection where the name.middle field has been successfully renamed to name.middleName.

Conclusion

The $rename operator in MongoDB is a versatile tool for updating field names within documents, accommodating embedded/nested structures and arrays. This operator’s ability to handle both renaming and conditional operations makes it useful for maintaining and organizing document structures. By utilizing methods such as update() and findAndModify() developers can efficiently manage field names and ensure data integrity within their MongoDB collections.

FAQs on MongoDB $rename

Is it possible for the $rename operator to rename multiple fields simultaneously?

Yes, the $rename operator can rename multiple fields simultaneously by specifying each field and its new name within the same command.

What happens if the new field name already exists in the document?

If the new field name already exists, the $rename operator will remove the existing field before renaming the specified field to the new name.

Can the $rename operator be used on embedded documents or arrays?

Yes, the $rename operator can be used on embedded/nested documents or arrays, allowing for renaming fields within these structures or moving fields in and out of them.



Previous Article
Next Article

Similar Reads

How to rename the collection name of MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
2 min read
How to Rename Collection in MongoDB?
Renaming a collection in MongoDB is a common task faced by developers and database administrators. In this article, we will learn the different methods to rename a collection in MongoDB, including the renameCollection() method and the db.runCommand() method. By the end of this article, we will have a clear understanding of how to rename a collectio
3 min read
How to Rename Fields in MongoDB
The $rename operator in MongoDB is a powerful tool used to rename field names within documents. It works by unsetting the old field name and setting the new one by preserving the document's atomicity but altering the field order. This operator is essential for managing and updating document structures dynamically. In this article, we will learn abo
5 min read
How to Rename a MongoDB Database?
Renaming a MongoDB database may be necessary for various reasons such as reorganization or clarity. MongoDB provides several methods for renaming a database including using shell commands, dumping and restoring data or directly manipulating database files. In this article, we will learn different approaches to renaming a MongoDB database by Underst
4 min read
Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
How to Integrate MongoDB Atlas and Segment using MongoDB Stitch
Data integration has become a crucial component of modern business strategies, allowing companies to enhance the power of data for informed decision-making. According to a recent survey, 85% of businesses believe that integrating data across multiple platforms is important for their success. In this article, We will learn about What is MongoDB Stit
5 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read
MongoDB Shell vs MongoDB Node.JS Driver
MongoDB Shell and the MongoDB Node.js Driver are both tools for interacting with MongoDB, but they serve different purposes and are used in different contexts. Here's a comparison of the two: MongoDB Node.JS DriverA Node.js package called the MongoDB Node.js Driver enables programmatic communication between applications and MongoDB databases. Throu
4 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
MongoDB AND operator ( $and )
MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. ac
2 min read
MongoDB NOT operator ( $not )
MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression. It also includes those documents that don't contain the field. You can
2 min read
MongoDB OR operator ( $or )
MongoDB provides different types of logical query operators and $or operator is one of them. This operator is used to perform logical OR operation on the array of two or more expressions and select or retrieve only those documents that match at least one of the given expression in the array. You can use this operator in methods like find(), update(
2 min read
MongoDB NOR operator ( $nor )
MongoDB provides different types of logical query operators and $nor operator is one of them. This operator is used to perform logical NOR operation on the array of one or more expressions and select or retrieve only those documents that do not match all the given expression in the array. You can use this operator in methods like find(), update(),
2 min read
MongoDB - Current Date Operator ($currentDate)
MongoDB provides different types of field update operators to update the values of the fields of the documents and $currentDate operator is one of them. This operator is used to set the value of a field to the current date (either as a timestamp or as a Date). The default type of $currentDate operator is a Date. This operator can also work with emb
2 min read
MongoDB $ln Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and $ln operator is one of them. This operator is used to find the natural logarithm of a number and returns the result as a double. Syntax: { $ln: <number> } Here, the number is a valid expression until it resolves to a non- n
1 min read
MongoDB $sqrt Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages $sqrt operator is one of them. This operator is used to find the square root of a positive number and returns the result as a double. Syntax: { $sqrt: <number> } Here, the number is a valid expression until it resolves to a non
2 min read
MongoDB $mod Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and $mod operator is one of them. This operator is used to divide one number by another number and return the remainder. Syntax: { $mod: [ <expression1>, <expression2> ] } Here, in this operator, the arguments passed in a
1 min read
MongoDB - $ne Operator
MongoDB $ne or "not equals" operator is one of the comparison operators. The $ne operator selects those documents where the field value is not equal to the given value. It also includes those documents that do not contain the specified field. You can use this operator in methods like find(), update(), etc. as per your requirement. Syntax{field: {$n
2 min read
MongoDB - $nin Operator
MongoDB $nin or " not in" is one of the comparison query operators. The $nin operator selects those documents where the field value is not equal to any of the given values in the array and the field that does not exist. You can use this operator in methods like find(), update(), etc. according to your requirements. Syntax{field: {$nin: [value1, val
2 min read
MongoDB - $max Operator
MongoDB $max or maximum operator is one of the field update operators. $max operator updates the field with the specified value if the specified value is greater than the current value. Important Points This operator will compare the values of different data types according to the BSON comparison order.You can also use this operator in embedded/nes
3 min read
MongoDB - $min operator
MongoDB $min or minimum operator is one of the field update operators. $min operator updates the field with the specified value if the specified value is less than the current value. The $min operator will compare the values of different data types according to the BSON comparison order. This operator can also be used in embedded/nested documents u
3 min read
MongoDB - $inc Operator
MongoDB $inc or increment operator is a type of field update operator. $inc operator increases the values of the fields to the specified amount or increases the field by the given value. Important PointsThis operator accepts positive and negative values.If the given field does not exist, then this operator will create a field and set the value of t
2 min read
MongoDB - $lt Operator
MongoDB $lt operator or less than operator is one of the comparison operators. The $lt operator selects the documents with a value less than (<) the given value. You can use this operator in methods like, find(), update(), etc. as per your requirements. Syntax{field: {$lt: value}}MongoDB $lt Operator ExampleIn the following examples, we are work
2 min read
MongoDB - $lte Operator
MongoDB $lte Operator is one of the comparison operators. $lte operator selects those documents where the field value is less than equal to (<=) the given value. This operator can be used in methods like find(), update(), etc. according to your requirements.. Syntax{field: {$lte: value}}MongoDB $lte Operator ExampleIn the following examples, we
2 min read
How to use the $lookup operator in aggregation pipelines in MongoDB?
One of the essential stages of the Aggregation Pipeline is the $lookup. It enables us to accomplish a left outer join between two collections. This step is quite beneficial when we have to compose data from different collections into a single document. The Aggregation Pipeline in MongoDB is a robust tool that allows us to manipulate and analyze dat
4 min read
MongoDB $gt Operator
MongoDB $gt operator selects documents where the value of a field is greater than a specified value. $gt Operator in MongoDBThe $gt operator in MongoDB is a comparison operator. It is used to find documents where the value in the field is greater than(>) a given value. This operator can be used with other methods like find, update, etc. accordin
2 min read
MongoDB - $gte Operator
MongoDB $gte or "greater than equals to" operator is one of the comparison operators. $gte operator selects those documents where the field value is greater than equals to(>=) the given value. This operator can be used in methods (like, find(), update(), etc.) according to your requirements. Syntax{field: {$gte: value}}MongoDB $gte Operator Exam
2 min read
MongoDB - $eq Operator
MongoDB $eq operator or equality operator is a comparison operator. The $eq operator matches documents where the value of the field is equal to the specified value. Important Points: If the given value is a document, then the order of the fields in the document is important.If the given value is an array, then MongoDB matches the documents where th
2 min read
MongoDB - $concat Operator
The $concat operator in MongoDB is a useful tool for string manipulation within aggregation pipelines. It allows us to concatenate strings or expressions to create new fields or modify existing ones. In this article, We will learn about the $concat operator in MongoDB by understanding various examples in detail. MongoDB - $concat OperatorThe $conca
3 min read