The $set operator is used to change or add specific fields in a document without replacing the whole document.
$set operator for setting fields in MongoDB
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
MongoDB
db.collection.updateOne(
{ <filter> },
{ $set: { <field1>: <value1>, <field2>: <value2>, ... } }
)The updateOne method updates a single document matching the filter.
The $set operator only changes the specified fields and leaves others untouched.
Examples
MongoDB
db.users.updateOne(
{ username: "alice" },
{ $set: { email: "alice@example.com" } }
)MongoDB
db.products.updateOne(
{ productId: 123 },
{ $set: { price: 19.99, stock: 50 } }
)MongoDB
db.orders.updateOne(
{ orderId: 456 },
{ $set: { status: "shipped" } }
)Sample Program
This example first adds an employee named John. Then it updates John's role and active status using $set. Finally, it retrieves John's updated document.
MongoDB
db.employees.insertOne({ name: "John", role: "Developer", active: true })
db.employees.updateOne(
{ name: "John" },
{ $set: { role: "Senior Developer", active: false } }
)
db.employees.find({ name: "John" }).toArray()Important Notes
If the field does not exist, $set will add it to the document.
Using $set prevents overwriting the entire document, which can avoid accidental data loss.
Summary
$set changes or adds specific fields in a document.
It is used with update methods like updateOne or updateMany.
Only the fields inside $set are affected; others stay the same.
Practice
1. What does the
$set operator do in MongoDB?easy
Solution
Step 1: Understand the purpose of
The$set$setoperator is used to update existing fields or add new fields in a MongoDB document without affecting other fields.Step 2: Compare with other operations
Deleting fields uses$unset, replacing documents usesreplaceOne, and creating collections is unrelated to$set.Final Answer:
It updates the value of specified fields or adds them if they don't exist. -> Option AQuick Check:
$setupdates 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
Solution
Step 1: Identify correct
The$setsyntax$setoperator requires an object with field-value pairs inside curly braces: {$set: {field: value}}.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.Final Answer:
db.collection.updateOne({name: 'John'}, {$set: {age: 30}}) -> Option BQuick Check:
Correct$setsyntax 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
Solution
Step 1: Understand
The$seteffect on fields$setoperator updates existing fields and adds new fields without removing others.Step 2: Apply update to the document
Fieldcitychanges from 'Paris' to 'London', and new fieldagewith value 25 is added. Thenamefield remains unchanged.Final Answer:
{ name: 'Alice', city: 'London', age: 25 } -> Option CQuick Check:
$setupdates 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
Solution
Step 1: Analyze the $set object
The$setoperator requires each field to have a value. Here,stockis listed without a value, which is invalid syntax.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.Final Answer:
Missing value for the field 'stock' inside $set causes a syntax error. -> Option AQuick 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
Solution
Step 1: Identify condition to update only missing 'status'
The filter {status: {$exists: false}} selects documents where the 'status' field does not exist.Step 2: Use $set to add 'status' field
The update {$set: {status: 'active'}} adds the 'status' field with value 'active' only to those documents.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.Final Answer:
db.employees.updateMany({status: {$exists: false}}, {$set: {status: 'active'}}) -> Option DQuick 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
