Rename a Field In MongoDB Documents

mongodb rename field mongodb rename field mongo shell command rename field mongo cli

Today in this article, we shall learn MongoDB – how to rename a field in Documents in MongoDB.

We will perform Rename a field/property for all the documents in the database and we will also see Rename specific field/property conditionally

We will cover below aspects below,

I have below Mongo Collection where my fields are defined as below.

I have a field name called “EmpID” which I want to rename to “EmpNumber

MongoDB Rename A Field in Documents Mongoose Rename a Field in DocumentsMongoDB How to Rename a Field in Documents

Let’s get started step by step details on how to achieve rename.

Please open the command prompt or PowerShell and log in to your database using a connection string.

We will first login to MongoDB and then switch to using the required database and the collection

use <DBName>
Mongo rename fieldMongoDB How to Rename a Field in Documents

Command Pattern

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

You can specify one or multiple fields for the renaming support.

Rename a field for all the documents in the database

Command:

db.employee.update({}, { $rename: { "EmpID": "EmpNumber" } },false, true );

OR

db.employee.updateMany({}, { $rename: { "EmpID": "EmpNumber" } },false, true ); 

Example

db.employee.update({}, { $rename: { “EmpID”: “EmpNumber” } },false, true );
WriteResult({ “nMatched” : 4, “nUpserted” : 0, “nModified” : 4 })

MongoDB Rename A Field

Rename a field for all the documents in the database

Rename fields for the matching criteria in the database

We can rename fields based on some filter criteria. Example – Below we are renaming the fields when “Name” fields match with a value i.e “John“.

Example

db.employee.update({“Name”:”John”}, { $rename: { “EmpNumber”: “EmpID” } },false, true )
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })

MongoDB Rename A Field

Rename specific fields for hierarchal criteria in the database

If you have nested objects defined in the schema then one can use the below convention to perform rename.

Example

db.employee.update({}, {$rename:{"Employee.EmpID":"Employee.EmpNumber"}}, false, true);

OR

db.employee.updateMany({}, {$rename:{"Employee.EmpID":"Employee.EmpNumber"}}, false, true); 

References:

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *