0
0
MongoDBquery~5 mins

Single document atomicity in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Single document atomicity
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
1010 operations
100100 operations
10001000 operations

Pattern observation: More fields mean more work, growing steadily with document size.

Final Time Complexity

Time Complexity: O(n)

This means updating a single document takes time proportional to the document's size.

Common Mistake

[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.

Interview Connect

Knowing how single document updates scale helps you explain database behavior clearly and confidently.

Self-Check

"What if the update changed multiple nested fields instead of just one? How would the time complexity change?"