Rename a Field In MongoDB Documents
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“
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>
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 })
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 })
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.