0
0
MongoDBquery~5 mins

$rename operator for field names in MongoDB

Choose your learning style9 modes available
Introduction

The $rename operator helps you change the names of fields in your MongoDB documents easily.

You want to fix a typo in a field name across many documents.
You need to update field names to match a new data format.
You want to make field names more descriptive or consistent.
You are merging data and want to avoid field name conflicts.
You want to remove old field names and replace them with new ones.
Syntax
MongoDB
db.collection.updateMany(
  { <filter> },
  { $rename: { "oldFieldName": "newFieldName" } }
)

The $rename operator is used inside an update command.

You can rename multiple fields by adding more pairs inside the $rename object.

Examples
This renames the field username to user_name in all documents in the users collection.
MongoDB
db.users.updateMany({}, { $rename: { "username": "user_name" } })
This renames price to cost and desc to description only for documents where category is "books".
MongoDB
db.products.updateMany(
  { "category": "books" },
  { $rename: { "price": "cost", "desc": "description" } }
)
Sample Program

This example creates a collection items with two documents. It then renames the field price to cost in all documents. Finally, it shows the updated documents.

MongoDB
use shopDB

// Insert sample documents
db.items.insertMany([
  { _id: 1, name: "Pen", price: 1.5 },
  { _id: 2, name: "Notebook", price: 3.0 }
])

// Rename field 'price' to 'cost'
db.items.updateMany({}, { $rename: { "price": "cost" } })

// Find all documents to see the change
db.items.find().pretty()
OutputSuccess
Important Notes

If the new field name already exists in a document, $rename will overwrite it.

You cannot rename a field to the same name it already has.

Summary

$rename changes field names in MongoDB documents.

It works inside update commands like updateMany.

You can rename one or many fields at once.