MongoDB — Transactions
Basic Transaction
const session = client.startSession();
session.startTransaction();
try {
db.orders.insertOne({ userId: ObjectId("..."), total: 100 }, { session });
db.inventory.updateOne({ _id: ObjectId("...") }, { $inc: { stock: -1 } }, { session });
session.commitTransaction();
} catch (error) {
session.abortTransaction();
} finally {
session.endSession();
}
Transaction Requirements
| Requirement | Description |
|---|---|
| Replica set | Required for transactions |
| Storage engine | WiredTiger |
| Time limit | 60 seconds default |
Retry Logic
const session = client.startSession();
for (let retry = 0; retry < 3; retry++) {
try {
session.startTransaction();
// Operations
await session.commitTransaction();
break;
} catch (error) {
if (error.errorCode === 112) { // WriteConflict
continue;
}
throw error;
}
}
Mini Practice
- Start a transaction
- Commit transaction
- Abort transaction
- Add retry logic
Up Next
Continue with Validation — document validation.
Related Topics
Frequently Asked Questions about Transactions
What is Transactions in MongoDB?
Transactions is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Transactions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Transactions.
Why is Transactions important in MongoDB?
Transactions is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.