0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Rename Field in Document

Use the $rename operator in an update command like db.collection.updateMany({}, { $rename: { 'oldField': 'newField' } }) to rename a field in MongoDB documents.
📋

Examples

InputDocument: { name: 'Alice', age: 25 }, Rename 'age' to 'years'
Output{ name: 'Alice', years: 25 }
InputDocument: { title: 'Book', author: 'Bob' }, Rename 'author' to 'writer'
Output{ title: 'Book', writer: 'Bob' }
InputDocument: { product: 'Pen', price: 1.5 }, Rename 'cost' to 'price' (field does not exist)
Output{ product: 'Pen', price: 1.5 }
🧠

How to Think About It

To rename a field in MongoDB, think of it as telling the database to change the label of a column in all matching documents. You use the $rename operator inside an update command to specify the old field name and the new field name. MongoDB then updates all documents accordingly without changing other data.
📐

Algorithm

1
Identify the collection where the documents are stored.
2
Specify the filter to select which documents to update (use {} for all documents).
3
Use the <code>$rename</code> operator with a mapping from old field name to new field name.
4
Run the update command to apply the rename operation.
5
Verify the documents to confirm the field has been renamed.
💻

Code

mongodb
db.collection.updateMany({}, { $rename: { 'oldField': 'newField' } })
print('Field renamed successfully')
Output
Field renamed successfully
🔍

Dry Run

Let's trace renaming 'age' to 'years' in a document { name: 'Alice', age: 25 }

1

Select documents

Filter is {}, so all documents including { name: 'Alice', age: 25 } are selected

2

Apply $rename

Rename field 'age' to 'years' in the selected document

3

Result

Document becomes { name: 'Alice', years: 25 }

StepDocument BeforeOperationDocument After
1{ name: 'Alice', age: 25 }$rename 'age' to 'years'{ name: 'Alice', years: 25 }
💡

Why This Works

Step 1: Using $rename operator

The $rename operator tells MongoDB to change the name of a field from the old name to the new name.

Step 2: Update command applies changes

The updateMany command applies this rename to all documents matching the filter.

Step 3: No data loss

Only the field name changes; the field's value and other fields remain unchanged.

🔄

Alternative Approaches

Aggregation Pipeline with $addFields and $unset
mongodb
db.collection.updateMany({}, [
  { $addFields: { newField: '$oldField' } },
  { $unset: 'oldField' }
])
This method renames by copying the old field to a new field and removing the old one; it can be slower but allows complex transformations.
Manual document update in application code
mongodb
// Fetch documents, rename field in code, then replace documents
This approach is less efficient and more error-prone but useful if complex logic is needed during rename.

Complexity: O(n) time, O(1) space

Time Complexity

The update operation must scan and modify each matching document once, so it is linear in the number of documents updated.

Space Complexity

The rename happens in place without extra storage, so space complexity is constant.

Which Approach is Fastest?

Using $rename is the fastest and simplest method compared to aggregation or manual updates.

ApproachTimeSpaceBest For
$rename operatorO(n)O(1)Simple field renames in many documents
Aggregation pipelineO(n)O(1)Renames with complex transformations
Manual update in codeO(n)O(n)Complex logic but less efficient
💡
Always back up your data before running bulk rename operations to avoid accidental data loss.
⚠️
Trying to rename a field that does not exist will not cause an error but will not change anything either.