Single document atomicity in MongoDB - Time & Space Complexity
We want to understand how the time to update a single document changes as the document size grows.
How does MongoDB handle updates inside one document in terms of speed?
Analyze the time complexity of the following code snippet.
db.collection.updateOne(
{ _id: 123 },
{ $set: { "profile.name": "Alice", "profile.age": 30 } }
)
This code updates fields inside a single document identified by its unique _id.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Access and update fields inside one document.
- How many times: Once per update, no loops over multiple documents.
As the document size grows, the time to update a field inside it grows roughly in a straight line.
| Input Size (document fields) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: More fields mean more work, growing steadily with document size.
Time Complexity: O(n)
This means updating a single document takes time proportional to the document's size.
[X] Wrong: "Updating one document always takes the same time no matter its size."
[OK] Correct: Larger documents need more work to find and update fields, so time grows with size.
Knowing how single document updates scale helps you explain database behavior clearly and confidently.
"What if the update changed multiple nested fields instead of just one? How would the time complexity change?"