Multi-document transactions in MongoDB - Time & Space 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.
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 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.
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 |
|---|---|
| 3 | 3 database commands |
| 10 | 10 database commands |
| 100 | 100 database commands |
Pattern observation: The time grows linearly as you add more operations inside the transaction.
Time Complexity: O(n)
This means the time to complete the transaction grows in a straight line with the number of operations inside it.
[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.
Understanding how transaction time grows helps you design efficient database operations and shows you can think about performance in real projects.
"What if we used transactions with many read operations instead of writes? How would the time complexity change?"