Transactions vs atomic document writes in MongoDB - Performance Comparison
Start learning this pattern below
Jump into concepts and practice - no test required
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.
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 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.
As the number of documents to update grows, atomic writes stay simple but transactions handle more steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 document | 1 update operation |
| 10 documents | 10 update operations inside transaction |
| 100 documents | 100 update operations inside transaction |
Pattern observation: Atomic writes handle one document quickly; transactions grow linearly with documents updated.
Time Complexity: O(n)
This means the time grows roughly in direct proportion to the number of documents updated in the transaction.
[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.
Understanding how transactions scale helps you explain trade-offs in real projects where data consistency matters.
"What if we used bulk writes instead of transactions? How would the time complexity change?"
Practice
Solution
Step 1: Understand atomic writes scope
Atomic writes in MongoDB apply only to single documents, ensuring full update or no update.Step 2: Compare with multi-document operations
Multi-document updates require transactions, not atomic writes.Final Answer:
They update a single document completely or not at all. -> Option DQuick Check:
Atomic writes = single document update [OK]
- Thinking atomic writes cover multiple documents
- Confusing atomic writes with transactions
- Assuming partial updates are atomic
Solution
Step 1: Recall MongoDB transaction syntax
Transactions start on a session object using startTransaction() method.Step 2: Verify options
Only session.startTransaction() matches the correct syntax.Final Answer:
session.startTransaction() -> Option AQuick Check:
Start transaction = session.startTransaction() [OK]
- Using db.startTransaction() which is invalid
- Confusing method names like transaction.begin()
- Incorrect method call syntax
const session = client.startSession();
session.startTransaction();
try {
await collection.updateOne({ _id: 1 }, { $set: { value: 10 } }, { session });
await collection.updateOne({ _id: 2 }, { $set: { value: 20 } }, { session });
await session.commitTransaction();
} catch (e) {
await session.abortTransaction();
}Solution
Step 1: Understand transaction behavior
Transactions ensure all operations succeed or all fail together.Step 2: Analyze code flow
If any update fails, catch block aborts transaction, rolling back changes.Final Answer:
Both updates are applied or none if any fails. -> Option AQuick Check:
Transaction = all or nothing [OK]
- Assuming partial updates apply on failure
- Ignoring abortTransaction() effect
- Thinking updates apply independently
const session = client.startSession();
session.startTransaction();
await collection.updateOne({ _id: 1 }, { $set: { value: 10 } });
await session.commitTransaction();
session.endSession();Solution
Step 1: Check transaction usage in updateOne
Operations inside a transaction must include the session option to link them.Step 2: Verify code calls
updateOne lacks { session } option, so it runs outside transaction.Final Answer:
Missing session option in updateOne call. -> Option BQuick Check:
Include session in operations inside transactions [OK]
- Forgetting to pass session option in operations
- Calling endSession before commitTransaction
- Misordering startTransaction call
Solution
Step 1: Identify multi-document update requirement
Updating two collections means multiple documents involved.Step 2: Choose appropriate method
Transactions ensure both updates succeed or fail together, preserving consistency.Final Answer:
Use a transaction to update both collections atomically. -> Option CQuick Check:
Multi-document update = use transactions [OK]
- Using atomic writes for multiple collections
- Ignoring failure possibility in one update
- Assuming separate writes are automatically atomic
