$set operator for setting fields in MongoDB - Time & Space Complexity
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?"