0
0
MongoDBquery~5 mins

Transactions vs atomic document writes in MongoDB - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Transactions vs atomic document writes
O(n)
Understanding Time Complexity

When working with MongoDB, it's important to know how operations take time as data grows.

We want to see how transactions compare to atomic document writes in terms of time cost.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

// Atomic document write
db.collection.updateOne(
  { _id: 1 },
  { $set: { field: 'value' } }
);

// Multi-document transaction
const session = client.startSession();
session.startTransaction();
try {
  db.collection1.updateOne({ _id: 1 }, { $set: { field: 'value' } }, { session });
  db.collection2.updateOne({ _id: 2 }, { $set: { field: 'value' } }, { session });
  await session.commitTransaction();
} finally {
  session.endSession();
}

This code shows a simple atomic update on one document versus a transaction updating multiple documents.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single document update for atomic write; multiple document updates inside a transaction.
  • How many times: Atomic write updates one document once; transaction updates multiple documents sequentially.
How Execution Grows With Input

As the number of documents to update grows, atomic writes stay simple but transactions handle more steps.

Input Size (n)Approx. Operations
1 document1 update operation
10 documents10 update operations inside transaction
100 documents100 update operations inside transaction

Pattern observation: Atomic writes handle one document quickly; transactions grow linearly with documents updated.

Final Time Complexity

Time Complexity: O(n)

This means the time grows roughly in direct proportion to the number of documents updated in the transaction.

Common Mistake

[X] Wrong: "Transactions are always slower than atomic writes regardless of how many documents are involved."

[OK] Correct: Transactions add overhead but if you update many documents, doing them separately can be slower or inconsistent. The time depends on how many documents are updated, not just the use of transactions.

Interview Connect

Understanding how transactions scale helps you explain trade-offs in real projects where data consistency matters.

Self-Check

"What if we used bulk writes instead of transactions? How would the time complexity change?"