Bird
Raised Fist0
MongoDBquery~10 mins

$rename operator for field names in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - $rename operator for field names
Start with original document
↓
Apply $rename operator
↓
Check each field in $rename
↓
Rename field if exists
↓
Create new field with old value
↓
Remove old field
↓
Return updated document
The $rename operator changes field names in a document by copying the value to a new field and removing the old field.
Execution Sample
MongoDB
db.collection.updateOne(
  { _id: 1 },
  { $rename: { "oldName": "newName" } }
)
This updates the document with _id 1 by renaming the field 'oldName' to 'newName'.
Execution Table
StepDocument StateActionResult
1{ _id: 1, oldName: "value", otherField: 123 }Start with original documentDocument unchanged
2{ _id: 1, oldName: "value", otherField: 123 }Check if 'oldName' existsYes, field found
3{ _id: 1, oldName: "value", otherField: 123 }Copy 'oldName' value to 'newName'{ _id: 1, oldName: "value", newName: "value", otherField: 123 }
4{ _id: 1, oldName: "value", newName: "value", otherField: 123 }Remove 'oldName' field{ _id: 1, newName: "value", otherField: 123 }
5{ _id: 1, newName: "value", otherField: 123 }Return updated documentUpdate complete
💡 All fields in $rename processed; document updated with renamed fields.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
Document{ _id: 1, oldName: "value", otherField: 123 }{ _id: 1, oldName: "value", newName: "value", otherField: 123 }{ _id: 1, newName: "value", otherField: 123 }{ _id: 1, newName: "value", otherField: 123 }
Key Moments - 2 Insights
Why does the document temporarily have both 'oldName' and 'newName' fields during the rename?
Because $rename first copies the value to the new field before removing the old field, as shown in execution_table step 3 and 4.
What happens if the field to rename does not exist in the document?
No change occurs for that field; the document remains the same since $rename only affects existing fields (not shown in this trace but implied).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the document state after step 3?
A{ _id: 1, newName: "value", otherField: 123 }
B{ _id: 1, oldName: "value", newName: "value", otherField: 123 }
C{ _id: 1, oldName: "value", otherField: 123 }
D{ _id: 1, otherField: 123 }
💡 Hint
Check the 'Document State' column in execution_table row for step 3.
At which step is the 'oldName' field removed from the document?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column in execution_table to find when 'oldName' is removed.
If the document did not have 'oldName' field, what would happen?
AA new field 'newName' with null value would be added
BThe document would be deleted
CThe document would remain unchanged
DAn error would occur
💡 Hint
Recall that $rename only affects existing fields; absence means no change.
Concept Snapshot
$rename operator syntax:
{ $rename: { "oldField": "newField" } }

Behavior:
- Copies value from oldField to newField
- Removes oldField
- Only affects existing fields

Use in update operations to rename fields in documents.
Full Transcript
The $rename operator in MongoDB updates documents by changing field names. It works by copying the value from the old field to a new field, then removing the old field. This process ensures the data is preserved under the new name. The execution steps start with the original document, check if the old field exists, copy its value to the new field, remove the old field, and finally return the updated document. If the old field does not exist, the document remains unchanged. This operator is useful for renaming fields without losing data.

Practice

(1/5)
1. What does the $rename operator do in MongoDB?
easy
A. It changes the value of a field in documents.
B. It deletes a field from documents.
C. It changes the name of a field in documents.
D. It adds a new field to documents.

Solution

  1. Step 1: Understand the purpose of $rename

    The $rename operator is used to change the name of an existing field in MongoDB documents.
  2. Step 2: Compare with other update operators

    Unlike $unset which deletes fields, or $set which changes values or adds fields, $rename only changes field names.
  3. Final Answer:

    It changes the name of a field in documents. -> Option C
  4. Quick Check:

    $rename changes field names [OK]
Hint: Remember: $rename changes field names, not values or deletion [OK]
Common Mistakes:
  • Confusing $rename with $set or $unset
  • Thinking $rename changes field values
  • Assuming $rename adds new fields
2. Which of the following is the correct syntax to rename the field oldName to newName in all documents of a collection named users?
easy
A. db.users.updateMany({}, { $rename: { oldName: newName } })
B. db.users.updateMany({}, { $rename: { oldName: 'newName' } })
C. db.users.updateMany({}, { $rename: { 'oldName': newName } })
D. db.users.updateMany({}, { $rename: { 'oldName': 'newName' } })

Solution

  1. Step 1: Check the syntax for $rename

    The $rename operator requires a mapping object where both old and new field names are strings, so keys and values must be quoted.
  2. Step 2: Validate each option

    db.users.updateMany({}, { $rename: { 'oldName': 'newName' } }) correctly uses quotes around both 'oldName' and 'newName'. Options A, C, and D miss quotes on either key or value, causing syntax errors.
  3. Final Answer:

    db.users.updateMany({}, { $rename: { 'oldName': 'newName' } }) -> Option D
  4. Quick Check:

    Field names in $rename must be strings [OK]
Hint: Always quote both old and new field names in $rename [OK]
Common Mistakes:
  • Not quoting field names as strings
  • Using variables instead of strings
  • Mixing quotes and no quotes
3. Given the collection products with documents:
{ "_id": 1, "name": "Pen", "cost": 5 }

What will be the document after running:
db.products.updateOne({ _id: 1 }, { $rename: { "cost": "price" } })

and then fetching the document with db.products.findOne({ _id: 1 })?
medium
A. { "_id": 1, "name": "Pen", "price": 5 }
B. { "_id": 1, "name": "Pen", "cost": 5, "price": 5 }
C. { "_id": 1, "name": "Pen" }
D. { "_id": 1, "name": "Pen", "cost": 5 }

Solution

  1. Step 1: Understand what $rename does in updateOne

    The $rename operator changes the field name from cost to price in the matched document.
  2. Step 2: Predict the document after update

    The field cost is removed and replaced by price with the same value 5. Other fields remain unchanged.
  3. Final Answer:

    { "_id": 1, "name": "Pen", "price": 5 } -> Option A
  4. Quick Check:

    $rename moves field value to new name [OK]
Hint: Rename moves value, old field disappears [OK]
Common Mistakes:
  • Expecting both old and new fields to exist
  • Thinking $rename changes field values
  • Assuming $rename deletes other fields
4. You run the following command:
db.orders.updateMany({}, { $rename: { "orderDate": "date" } })

but get an error. What is the most likely cause?
medium
A. The collection orders does not exist.
B. The new field name "date" already exists in some documents.
C. Field names in $rename must be quoted strings.
D. The updateMany command requires a filter other than {}.

Solution

  1. Step 1: Analyze the error cause for $rename

    If the new field name already exists in documents, MongoDB throws an error because it cannot rename a field to an existing field name.
  2. Step 2: Check other options

    Field names in $rename must be quoted strings. is incorrect because field names are quoted correctly. The collection orders does not exist. is unlikely as the error is specific to $rename. The updateMany command requires a filter other than {}. is invalid because {} is a valid filter for updateMany.
  3. Final Answer:

    The new field name "date" already exists in some documents. -> Option B
  4. Quick Check:

    $rename fails if new field exists [OK]
Hint: Cannot rename to existing field name [OK]
Common Mistakes:
  • Ignoring existing fields with new name
  • Assuming empty filter is invalid
  • Confusing syntax errors with runtime errors
5. You have a collection employees with documents containing fields fname and lname. You want to rename fname to firstName and lname to lastName in one update command. Which command correctly does this?
hard
A. db.employees.updateMany({}, { $rename: { 'fname': 'firstName', 'lname': 'lastName' } })
B. db.employees.updateMany({}, { $rename: { 'fname': 'firstName' }, { 'lname': 'lastName' } })
C. db.employees.updateMany({}, { $rename: { fname: 'firstName', lname: 'lastName' } })
D. db.employees.updateMany({}, { $rename: { 'fname': firstName, 'lname': lastName } })

Solution

  1. Step 1: Understand $rename supports multiple fields

    The $rename operator accepts an object mapping old field names to new field names, allowing multiple renames in one command.
  2. Step 2: Check syntax correctness

    db.employees.updateMany({}, { $rename: { 'fname': 'firstName', 'lname': 'lastName' } }) correctly uses a single object with quoted old and new field names. db.employees.updateMany({}, { $rename: { 'fname': 'firstName' }, { 'lname': 'lastName' } }) has invalid syntax with two separate objects. db.employees.updateMany({}, { $rename: { fname: 'firstName', lname: 'lastName' } }) misses quotes on keys. db.employees.updateMany({}, { $rename: { 'fname': firstName, 'lname': lastName } }) misses quotes on new field names.
  3. Final Answer:

    db.employees.updateMany({}, { $rename: { 'fname': 'firstName', 'lname': 'lastName' } }) -> Option A
  4. Quick Check:

    Multiple renames use one $rename object with string keys and values [OK]
Hint: Use one $rename object with all old:new pairs quoted [OK]
Common Mistakes:
  • Trying multiple $rename objects in one update
  • Not quoting new field names
  • Using variables instead of strings
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard