Careeroza
Transactions
๐น What are Multi-Document Transactions?
A transaction is a group of operations that are executed together as a single unit.
In MongoDB, multi-document transactions allow you to:
- Perform multiple operations
- Across multiple documents/collections
- And ensure all succeed or all fail
Simple:
All operations succeed OR none are applied
๐น Why Transactions are Needed
MongoDB normally works on single-document atomicity
But sometimes you need consistency across multiple documents
๐น Example
Bank transfer:
- Deduct money from Account A
- Add money to Account B
If one fails โ rollback everything
๐น Key Properties (ACID)
Transactions follow:
- Atomicity โ all or nothing
- Consistency โ data remains valid
- Isolation โ operations donโt interfere
- Durability โ changes are saved
๐น How it Works (Concept)
- Start transaction
- Perform multiple operations
- Commit โ save changes
- Abort โ rollback changes
๐น Important Points
- Works in replica sets and sharded clusters
- Slightly slower than normal operations
- Should be used only when needed
๐น When to Use
- Financial systems (banking)
- Order processing
- Critical multi-step operations
๐น When NOT to Use
- Simple operations
- When single document is enough
Simple Understanding
- Transaction = group of operations
- Multi-document = across multiple documents
- Ensures consistency