Video Transcript (English)
Welcome!
In this video, you’ll learn how to create multi-document transactions in MongoDB with a Python application.
A transaction is a group of database operations that are completed together as a unit or not at all.
Transactions are used when a group of related operations must either all succeed or all fail together. This property is known as atomicity.
Examples of transactions include transferring money with a mobile payment app, or taking an item from inventory and adding it to a shopping cart in an online shopping app.
Before we go through an example, let’s review the steps to complete a transaction in a Python application by using PyMongo’s callback API.
We’ll assume that we’ve already created a database connection. This is a prerequisite for creating a transaction.
First, we define the callback function that specifies the sequence of operations to perform inside the transaction.
Then we start a client session.
Finally, we’ll start the transaction by calling the with_transaction() method on the session object. `with_transaction` starts a transaction, executes the callback, and commits the transaction (or cancels if there’s an error). This helper method assists in reliably committing a transaction in the face of errors.
Note that by default, MongoDB will automatically cancel any multi-document transaction that runs for more than 60 seconds.
Now let’s go through an example.
Let’s say that we’re implementing a transaction in a banking context.
We’re working with a database named ‘bank’ that contains two collections: `accounts`, with account data, and `transfers`, with transfer data.
Coşkun Demirbaş is transferring $100 to Marcus Jørgensen.
These two documents contain data about their accounts prior to the transfer.
This data includes fields containing the account holder name, balance, account_id and the IDs of completed transfers.
Let’s think through the operations that are involved in this transaction: In the accounts collection, we’ll need to update the sender and receiver’s account documents with modified balances and new transfer id numbers. In the transfers collection, we’ll need to add a document with information about the transfer.
Because a single transfer involves updating multiple documents across two collections, we need a multi-document transaction to handle this set of operations.
Now that we know what this transaction will include, let’s go through the code.
We’ve already started a Python file and connected to our Atlas cluster with MongoClient.
First, we define the callback function that specifies the sequence of operations to perform inside the transaction.
The callback has one required parameter, which is the client session. We’ll create the client session in the next step.
If needed, we can also add parameters for our particular transaction. In our case, we have four keyword parameters specific to this bank transfer. They correspond to the transfer id number, account ids for the sender and receiver, and the transfer amount.
We’ll pass in the values specific to any particular transaction when we call the callback function.
Within our callback function, the first thing we’ll do is get references to the collections that our operations will take place on. This step is needed for any transaction that we create. In this case, we’ve created references to the accounts collection and the transfers_collection. Note that both references are accessed via the session object.
The rest of the callback function is defined specific to our use case.
Next, we create a transfer document, which we’ll insert into the `transfers` collection later in our code. This document contains the transfer id, account ids for the receiver and sender accounts, and the transfer amount.
Now we write our transaction operations. One important point is that we must pass the session to each operation.
We update the sender’s account document by using the update_one method.
To select the sender’s account, we filter by the sender’s account id.
There are two parts to the update.
First, we subtract the transfer amount from their balance. Notice that we use the $inc update operator to increment the balance by a negative amount.
Then, we add the transfer id to the ‘transfers_complete’ array field by using the $push update operator. Notice how we’ve passed the session to the operation.
The operation to update the receiver’s account document is structured in a similar way, but this time we’ll filter by the receiver’s account id.
Another important difference is that the receiver’s balance is increased. We use the $inc operator to increment the balance by the positive transfer amount.
In our final operation, we insert the transfer record into the ‘transfers’ collection.
Again, notice how we pass the session to all operations.
Finally, we print a confirmation message and return from the callback function.
Next, we’ll define a callback_wrapper function to pass in the custom keyword arguments for Coşkun and Marcus’ transfer.
The callback function is called with values for the transfer id, the account id of sender and receiver, and the transfer amount.
We’re passing in these values via the callback wrapper instead of assigning them within the callback itself. This is so that the callback function can be reusable for arbitrary transfers.
Note that the general best practice for passing arbitrary arguments to the callback is to use a lambda function. We’re using this callback wrapper for simplicity in this example.
We now move on to our last two steps: starting a client session and carrying out the transaction.
To start the client session, we call the `start_session` method on the `client` object in a with-statement.
To carry out the transaction, we call `with_transaction` on the `session` object. `with_transaction` starts a transaction, executes the callback, and commits (or cancels if there’s an error).
`with_transaction` has one required parameter, which is the callback function. In our case, we’re passing in the callback wrapper, which includes the custom keyword arguments for Coşkun and Marcus’ transfer.
If any of the steps in the transaction encounter an error, the transaction is canceled, and none of the changes are saved.
If the transaction is successful, the session will be closed automatically.
Finally, we close the client.
Let’s run the code. We get a message that says “Transaction successful” in the terminal.
This confirms that we have successfully transferred funds between the two accounts.
Well done! In this video, you learned how to create multi-document transactions in MongoDB with a Python application.