Bird
Raised Fist0
MongoDBquery~10 mins

$set operator for setting fields in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - $set operator for setting fields
Start with existing document
Apply $set operator
Check each field in $set
If field exists, update value
If field does not exist, add field with value
Save updated document
End
The $set operator updates specified fields in a document. It changes existing fields or adds new ones if they don't exist.
Execution Sample
MongoDB
db.collection.updateOne(
  { _id: 1 },
  { $set: { name: "Alice", age: 30 } }
)
This updates the document with _id 1, setting 'name' to 'Alice' and 'age' to 30.
Execution Table
StepDocument Before$set FieldsDocument AfterAction
1{ _id: 1, name: "Bob", city: "NY" }{ name: "Alice", age: 30 }{ _id: 1, name: "Alice", city: "NY", age: 30 }Updated 'name', added 'age'
2{ _id: 2, city: "LA" }{ name: "Alice", age: 30 }{ _id: 2, city: "LA", name: "Alice", age: 30 }Added 'name' and 'age'
3{ _id: 3, name: "Charlie", age: 25 }{ age: 30 }{ _id: 3, name: "Charlie", age: 30 }Updated 'age' only
4N/AN/AN/ANo more documents to update, operation ends
💡 All target documents processed, $set applied to each.
Variable Tracker
Document _idBefore $setAfter $set
1{ name: "Bob", city: "NY" }{ name: "Alice", city: "NY", age: 30 }
2{ city: "LA" }{ city: "LA", name: "Alice", age: 30 }
3{ name: "Charlie", age: 25 }{ name: "Charlie", age: 30 }
Key Moments - 2 Insights
Why does $set add new fields if they don't exist?
Because $set updates the document by changing existing fields or adding new ones if missing, as shown in execution_table rows 1 and 2.
What happens if $set updates a field that already exists?
The existing field's value is replaced with the new value, as seen in execution_table row 3 where 'age' changed from 25 to 30.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the 'age' value for document _id 1 after $set?
A25
Bnull
C30
DNot present
💡 Hint
Check the 'Document After' column for step 1 in execution_table.
At which step does $set add both 'name' and 'age' fields to a document that had neither?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Document Before' and 'Document After' columns in execution_table for step 2.
If we only $set { age: 35 } on document _id 3, what would be the 'age' after update?
A25
B35
C30
DField removed
💡 Hint
Refer to how $set updates existing fields in execution_table row 3.
Concept Snapshot
$set operator updates fields in a MongoDB document.
It replaces existing field values or adds new fields if missing.
Syntax: { $set: { field1: value1, field2: value2 } }
Used in update operations like updateOne or updateMany.
Does not remove fields, only sets or adds.
Full Transcript
The $set operator in MongoDB is used to update specific fields in documents. When you apply $set, it changes the value of existing fields or adds new fields if they don't exist. For example, if a document has a field 'name' with value 'Bob', using $set to set 'name' to 'Alice' will update it. If the document does not have an 'age' field, $set will add it with the specified value. This operation is commonly used in update commands like updateOne. The execution table shows step-by-step how documents change before and after applying $set. Key points include that $set never removes fields, only sets or adds them, and it works on each targeted document individually.

Practice

(1/5)
1. What does the $set operator do in MongoDB?
easy
A. It updates the value of specified fields or adds them if they don't exist.
B. It deletes specified fields from a document.
C. It replaces the entire document with a new one.
D. It creates a new collection in the database.

Solution

  1. Step 1: Understand the purpose of $set

    The $set operator is used to update existing fields or add new fields in a MongoDB document without affecting other fields.
  2. Step 2: Compare with other operations

    Deleting fields uses $unset, replacing documents uses replaceOne, and creating collections is unrelated to $set.
  3. Final Answer:

    It updates the value of specified fields or adds them if they don't exist. -> Option A
  4. Quick Check:

    $set updates or adds fields [OK]
Hint: Remember: $set changes or adds fields only [OK]
Common Mistakes:
  • Confusing $set with $unset which deletes fields
  • Thinking $set replaces the whole document
  • Assuming $set creates collections
2. Which of the following is the correct syntax to set the field age to 30 in a document using $set?
easy
A. db.collection.updateOne({name: 'John'}, {$set: [age: 30]})
B. db.collection.updateOne({name: 'John'}, {$set: {age: 30}})
C. db.collection.updateOne({name: 'John'}, {$set: 'age': 30})
D. db.collection.updateOne({name: 'John'}, {$set: age = 30})

Solution

  1. Step 1: Identify correct $set syntax

    The $set operator requires an object with field-value pairs inside curly braces: {$set: {field: value}}.
  2. Step 2: Check each option

    db.collection.updateOne({name: 'John'}, {$set: {age: 30}}) uses correct syntax with {age: 30}. Options A, B, and C use invalid JavaScript or MongoDB syntax.
  3. Final Answer:

    db.collection.updateOne({name: 'John'}, {$set: {age: 30}}) -> Option B
  4. Quick Check:

    Correct $set syntax uses object with field-value pairs [OK]
Hint: Use {$set: {field: value}} with curly braces [OK]
Common Mistakes:
  • Using assignment (=) inside $set
  • Using quotes incorrectly around field names
  • Using array brackets instead of object braces
3. Given the document { name: 'Alice', city: 'Paris' }, what will be the document after running db.users.updateOne({name: 'Alice'}, {$set: {city: 'London', age: 25}})?
medium
A. { city: 'London', age: 25 }
B. { name: 'Alice', city: 'Paris', age: 25 }
C. { name: 'Alice', city: 'London', age: 25 }
D. { name: 'Alice', city: 'London' }

Solution

  1. Step 1: Understand $set effect on fields

    The $set operator updates existing fields and adds new fields without removing others.
  2. Step 2: Apply update to the document

    Field city changes from 'Paris' to 'London', and new field age with value 25 is added. The name field remains unchanged.
  3. Final Answer:

    { name: 'Alice', city: 'London', age: 25 } -> Option C
  4. Quick Check:

    $set updates and adds fields, keeps others [OK]
Hint: Only fields in $set change; others stay same [OK]
Common Mistakes:
  • Assuming $set removes fields not listed
  • Thinking $set only adds but does not update
  • Confusing updateOne with replaceOne
4. You run this update: db.products.updateOne({id: 101}, {$set: {price: 20, stock}}). What is the problem?
medium
A. Missing value for the field 'stock' inside $set causes a syntax error.
B. The query filter {id: 101} is invalid.
C. You cannot update multiple fields with $set.
D. The update will delete the document.

Solution

  1. Step 1: Analyze the $set object

    The $set operator requires each field to have a value. Here, stock is listed without a value, which is invalid syntax.
  2. Step 2: Check other parts of the update

    The filter {id: 101} is valid, and $set can update multiple fields. The update does not delete documents.
  3. Final Answer:

    Missing value for the field 'stock' inside $set causes a syntax error. -> Option A
  4. Quick Check:

    Each field in $set must have a value [OK]
Hint: Every field in $set needs a value [OK]
Common Mistakes:
  • Leaving out values for fields in $set
  • Confusing filter syntax with update syntax
  • Thinking $set deletes documents
5. You want to update all documents in the employees collection to add a new field status with value 'active' only if the field status does not already exist. Which update command using $set is correct?
hard
A. db.employees.updateMany({}, {$set: {status: 'active'}})
B. db.employees.updateMany({status: {$ne: 'active'}}, {$set: {status: 'active'}})
C. db.employees.updateMany({status: null}, {$set: {status: 'active'}})
D. db.employees.updateMany({status: {$exists: false}}, {$set: {status: 'active'}})

Solution

  1. Step 1: Identify condition to update only missing 'status'

    The filter {status: {$exists: false}} selects documents where the 'status' field does not exist.
  2. Step 2: Use $set to add 'status' field

    The update {$set: {status: 'active'}} adds the 'status' field with value 'active' only to those documents.
  3. Step 3: Check other options

    db.employees.updateMany({}, {$set: {status: 'active'}}) updates all documents regardless of existing 'status'. db.employees.updateMany({status: null}, {$set: {status: 'active'}}) only matches documents with 'status' equal to null, not missing. db.employees.updateMany({status: {$ne: 'active'}}, {$set: {status: 'active'}}) updates documents where 'status' is not 'active', which may overwrite existing values.
  4. Final Answer:

    db.employees.updateMany({status: {$exists: false}}, {$set: {status: 'active'}}) -> Option D
  5. Quick Check:

    Use {$exists: false} to target missing fields [OK]
Hint: Filter with {$exists: false} to add missing fields only [OK]
Common Mistakes:
  • Updating all documents without filter
  • Using null instead of $exists for missing fields
  • Overwriting existing 'status' values unintentionally