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)

  1. Start transaction
  2. Perform multiple operations
  3. Commit โ†’ save changes
  4. 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