$set operator for setting fields in MongoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use the $set operator in MongoDB, it changes specific fields in documents.
We want to know how the time to do this changes when there are more documents or fields.
Analyze the time complexity of the following code snippet.
db.collection.updateMany(
{ status: "active" },
{ $set: { verified: true, lastChecked: new Date() } }
)
This code updates all documents with status "active" by setting two fields.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The database scans documents matching the filter and updates each one.
- How many times: Once for each matching document in the collection.
As the number of matching documents grows, the update work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 updates |
| 100 | About 100 updates |
| 1000 | About 1000 updates |
Pattern observation: The work grows directly with the number of documents to update.
Time Complexity: O(n)
This means the time to update grows in a straight line with the number of documents matched.
[X] Wrong: "Updating fields with $set is always instant no matter how many documents match."
[OK] Correct: Each matching document must be updated, so more documents mean more work and more time.
Understanding how updates scale helps you explain database performance clearly and confidently.
"What if we added an index on the status field? How would the time complexity change?"
Practice
$set operator do in MongoDB?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]
- Confusing $set with $unset which deletes fields
- Thinking $set replaces the whole document
- Assuming $set creates collections
age to 30 in a document using $set?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]
- Using assignment (=) inside $set
- Using quotes incorrectly around field names
- Using array brackets instead of object braces
{ name: 'Alice', city: 'Paris' }, what will be the document after running db.users.updateOne({name: 'Alice'}, {$set: {city: 'London', age: 25}})?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]
- Assuming $set removes fields not listed
- Thinking $set only adds but does not update
- Confusing updateOne with replaceOne
db.products.updateOne({id: 101}, {$set: {price: 20, stock}}). What is the problem?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]
- Leaving out values for fields in $set
- Confusing filter syntax with update syntax
- Thinking $set deletes documents
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?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]
- Updating all documents without filter
- Using null instead of $exists for missing fields
- Overwriting existing 'status' values unintentionally
