MongoDB Query to Rename Field in Document
$rename operator in an update command like db.collection.updateMany({}, { $rename: { 'oldField': 'newField' } }) to rename a field in MongoDB documents.Examples
How to Think About It
$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
Code
db.collection.updateMany({}, { $rename: { 'oldField': 'newField' } })
print('Field renamed successfully')Dry Run
Let's trace renaming 'age' to 'years' in a document { name: 'Alice', age: 25 }
Select documents
Filter is {}, so all documents including { name: 'Alice', age: 25 } are selected
Apply $rename
Rename field 'age' to 'years' in the selected document
Result
Document becomes { name: 'Alice', years: 25 }
| Step | Document Before | Operation | Document 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
db.collection.updateMany({}, [
{ $addFields: { newField: '$oldField' } },
{ $unset: 'oldField' }
])// Fetch documents, rename field in code, then replace documentsComplexity: 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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $rename operator | O(n) | O(1) | Simple field renames in many documents |
| Aggregation pipeline | O(n) | O(1) | Renames with complex transformations |
| Manual update in code | O(n) | O(n) | Complex logic but less efficient |