Problem Statement
Explain multi-document transactions in MongoDB. How do they ensure ACID properties and what are their limitations?
Explanation
Multi-document transactions in MongoDB allow you to execute multiple operations across multiple documents and collections atomically, ensuring ACID properties: Atomicity, Consistency, Isolation, and Durability. Either all operations in a transaction succeed and are committed, or all fail and are rolled back.
Atomicity means all operations in the transaction complete successfully or none do. If any operation fails, all previous operations are rolled back. Consistency ensures the database moves from one valid state to another. Isolation means concurrent transactions do not interfere with each other. Durability guarantees committed transactions survive system failures.
To use transactions, you start a session, begin a transaction, perform operations passing the session to each operation, and then commit or abort the transaction. MongoDB uses write-ahead logging and the oplog to implement transaction guarantees. During a transaction, changes are not visible to other operations until commit.
Transactions have important limitations. First, they are only available on replica sets and sharded clusters, not standalone instances. Second, they have a 60-second default timeout and are subject to the 16 MB oplog entry size limit. Third, transactions that affect multiple shards have additional overhead.
Fourth, transactions should be kept short because they hold locks on documents. Long-running transactions can block other operations and affect performance. Fifth, DDL operations like creating indexes cannot be performed inside transactions. Finally, transactions add latency compared to individual operations, so use them only when atomicity across multiple documents is truly required.
Code Solution
SolutionRead Only