Session and transaction syntax in MongoDB - Time & Space Complexity
When using sessions and transactions in MongoDB, it's important to know how the time to complete operations changes as data grows.
We want to understand how the cost of starting, running, and committing a transaction scales with the amount of work inside it.
Analyze the time complexity of the following MongoDB transaction code snippet.
const session = client.startSession();
session.startTransaction();
try {
await collection.updateOne({ _id: 1 }, { $set: { status: "active" } }, { session });
await collection.insertOne({ _id: 2, status: "pending" }, { session });
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
} finally {
await session.endSession();
}
This code starts a session, begins a transaction, performs two operations inside it, then commits or aborts the transaction.
Look for repeated or costly steps inside the transaction.
- Primary operation: Each database operation inside the transaction (updateOne, insertOne).
- How many times: Here, two operations are performed sequentially inside one transaction.
The time to complete the transaction grows roughly with the number of operations inside it.
| Input Size (number of operations) | Approx. Operations |
|---|---|
| 2 | 2 database calls + transaction overhead |
| 10 | 10 database calls + transaction overhead |
| 100 | 100 database calls + transaction overhead |
Pattern observation: More operations inside the transaction mean more work, so time grows roughly in direct proportion to the number of operations.
Time Complexity: O(n)
This means the time to complete the transaction grows linearly with the number of operations inside it.
[X] Wrong: "Starting a transaction adds a fixed big delay regardless of operations inside."
[OK] Correct: While starting a transaction has some overhead, the total time mostly depends on how many operations run inside it, not just the start.
Understanding how transaction time grows helps you design efficient database operations and shows you can think about performance in real projects.
"What if we added a loop to perform 100 updates inside one transaction? How would the time complexity change?"