MongoDB Documentation, Release 3.0.4 Background Pattern Overview Initialize Source and Destination Accounts db.accounts.insert( [ { _id: "A", balance: 1000, pendingTransactions: [] }, { _id: "B", balance: 1000, pendingTransactions: [] } ] ) The operation returns a BulkWriteResult() object with the status of the operation. Upon successful insert, the BulkWriteResult() has nInserted set to 2 . Chapter 3. MongoDB CRUD Operations 116 The examples in this tutorial use the following two collections: Insert into the accounts collection a document for account A and a document for account B . Consider a scenario where you want to transfer funds from account A to account B . In a relational database system, you can subtract the funds from A and add the funds to B in a single multi-statement transaction. In MongoDB, you can emulate a two-phase commit to achieve a comparable result. 1. A collection named accounts to store account information. 2. A collection named transactions to store information on the fund transfer transactions. • Atomicity: if one operation fails, the previous operation within the transaction must “rollback” to the previous state (i.e. the “nothing,” in “all or nothing”). • Consistency: if a major failure (i.e. network, hardware) interrupts the transaction, the database must be able to recover a consistent state. For situations that require multi-document transactions, you can implement two-phase commit in your application to provide support for these kinds of multi-document updates. Using two-phase commit ensures that data is consistent and, in case of an error, the state that preceded the transaction is recoverable (page 120). During the procedure, however, documents can represent pending data and states. Note: Because only single-document operations are atomic with MongoDB, two-phase commits can only offer transaction- like semantics. It is possible for applications to return intermediate data at intermediate points during the two-phase commit or rollback. Despite the power of single-document atomic operations, there are cases that require multi-document transactions. When executing a transaction composed of sequential operations, certain issues arise, such as: Operations on a single document are always atomic with MongoDB databases; however, operations that involve multi- ple documents, which are often referred to as “multi-document transactions”, are not atomic. Since documents can be fairly complex and contain multiple “nested” documents, single-document atomicity provides the necessary support for many practical use cases.