0
0
MongoDBquery~5 mins

Multi-document transactions in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Multi-document transactions
O(n)
Understanding Time Complexity

When using multi-document transactions in MongoDB, it's important to understand how the time to complete the transaction changes as you add more operations.

We want to know how the total work grows when the number of documents involved increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

const session = client.startSession();
session.startTransaction();
try {
  await collection1.updateOne({ _id: 1 }, { $set: { value: 10 } }, { session });
  await collection2.insertOne({ _id: 2, value: 20 }, { session });
  await collection3.deleteOne({ _id: 3 }, { session });
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}

This code performs multiple operations on different collections inside a single transaction.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Each database operation inside the transaction (updateOne, insertOne, deleteOne).
  • How many times: The number of operations equals the number of commands inside the transaction, here 3.
How Execution Grows With Input

As you add more operations inside the transaction, the total time grows roughly in direct proportion to the number of operations.

Input Size (n)Approx. Operations
33 database commands
1010 database commands
100100 database commands

Pattern observation: The time grows linearly as you add more operations inside the transaction.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the transaction grows in a straight line with the number of operations inside it.

Common Mistake

[X] Wrong: "Adding more operations inside a transaction does not affect the total time much because they run in parallel."

[OK] Correct: In reality, the operations inside a transaction run one after another, so each adds to the total time.

Interview Connect

Understanding how transaction time grows helps you design efficient database operations and shows you can think about performance in real projects.

Self-Check

"What if we used transactions with many read operations instead of writes? How would the time complexity change?"