Video Transcript (English)
Welcome!
In this video, you will learn how to create multi-document transactions in MongoDB for a Java application.
A multi-document transaction is an operation that requires atomicity of reads and/or writes to multiple documents.
A transaction is a sequence of database operations that represent a single unit of work. Once committed, all write operations performed under the protection of the transaction are saved. In the event that a transaction is canceled or doesn’t complete successfully, all write operations performed during the transaction are discarded.
Operations within a transaction succeed or fail together. This property is referred to as atomicity. Transactions also enable consistency, isolation, and durability of operations. These qualities together are known as ACID compliant.
Before we go through an example, let’s review the steps to complete a transaction in a Java application.
First, we start a client session. Next, we can define the transaction options, but this step is optional. Then, we define the sequence of operations to perform inside the transactions. To start the transaction, we use the ClientSession’s withTransaction() method. Finally, we release the resources used by the transaction.
Keep in mind that by default, MongoDB will automatically cancel any multi-document transaction that runs for more than 60 seconds.
Also, don’t forget to close any resources the transaction may use.
Now let’s go through an example. We’ll simulate a transaction by using the accounts collection. The transaction involves the transfer of funds from John Doe to Mary Doe.
For brevity we’ll assume that we have already instantiated the MongoClient.
When we write the code for all the transaction steps, the code does the following: Starts a client session. Defines the sequence of operations to perform inside the transaction. These operations start by getting all of the documents in the accounts collection. Then, a balance of 200 is withdrawn from one account and then deposited into another account. The balances in both accounts get updated, and a success message is printed after completion. Calls the withTransaction method to start a transaction, execute the callback, and commit.
If any of the steps in the transaction encounter an error, the transaction is canceled, and none of the changes are saved. It’s also important to note that by default a transaction has a maximum runtime of less than one minute.
Well done!
In this video, you learned how transactions are implemented in MongoDB with Java applications for atomic operations spanning multiple documents. Remember that it’s highly recommended that you close any resources used by the transaction.