MongoDB Rename Field
In databases, there are scenarios where you need to update the name of a field in an existing document without recreating the entire document.
In this post, we will discuss how to use the $rename operator to set a new name for an existing field.
Let’s jump in.
Operator Syntax
The following shows the syntax of the $rename operator in MongoDB:
The operator takes an existing field and assigns a new specified name.
The target name must differ from the source name. You can use the dot notation to rename a field in an embedded document or an array.
Let us look at a simple practical example to better understand how the $rename operator works.
Practical Example
Let us start by creating a sample collection and add sample documents as shown in the following query:
Add sample documents:
Now that we have a test data, we can proceed and discuss how to rename a field.
Example 1: Rename a Field Using the $rename Operator
The following example shows how to use the $rename operator to update the name of the field “qty” to “quantity”.
The command should return the acknowledgement status and the number of documents updated.
acknowledged: true,
insertedId: null,
matchedCount: 3,
modifiedCount: 3,
upsertedCount: 0
}
We can check the documents to verify that the specified field name has been updated.
Output documents:
{ _id: 1, product_name: 'product_1', price: 400, quantity: 7800 },
{ _id: 2, product_name: 'product_2', price: 4500, quantity: 344 },
{ _id: 3, product_name: 'product_3', price: 45, quantity: 200 }
]
Example 2: Rename a Non-Existent Field
If we use the $rename operator to rename an existent field, the operator does nothing and exists without an error.
An example is as shown in the following:
The previous command is simply completed without performing any action.
Conclusion
In this post, we explored how to rename an existing field in a MongoDB document using the $rename operator.
Thanks for reading!
Source: linuxhint.com