| by Arround The Web | No comments

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:

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

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:

db.createCollection(“products”)

Add sample documents:

db.products.insertMany([ { _id: 1, product_name: "product_1", price: 100, qty: 78 }, { _id: 2, product_name: "product_2", price: 4500, qty: 344 }, { _id: 3, product_name: "product_3", price: 45, qty: 200 }]);

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”.

db.products.updateMany( {}, { $rename: { "qty": "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.

test> db.products.find({}).pretty()

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:

db.students.updateMany( { _id: 1 }, { $rename: { 'wife': 'spouse' } } )

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!

Share Button

Source: linuxhint.com

Leave a Reply