MongoDB Transactions: Your Very First Transaction with MongoDB 4.0

MongoDB 4.0MongoDB 4.0 transactions is just around the corner and with rc0 we can get a good idea of what we can expect in the GA version. MongoDB 4.0 will allow transactions to run in a replica set and, in a future release, the MongoDB transaction will work for sharded clusters. This is a really big change!

Multi-statement transactions are a big deal for a lot of companies. The transactions feature has been in development since MongoDB version 3.0; in version 3.6 logical sessions were added. In an earlier blog post we highlighted a few details from what was delivered in 3.6 that indicated that 4.0 would have transactions.

There are a few limitations for transactions and some operations are not allowed yet. A detailed list can be found in the MongoDB documentation of the Session.startTransaction() method.

One restriction that we must be aware of is that the collection MUST exist in order to use transactions.

A simple transaction will be declared in a very similar way to that we use for other databases. The caveat is that we need to start a session before starting a transaction. This means that multi-statement transactions are not the default behavior to write to the database.

How to use transactions in MongoDB® 4.0

Download MongoDB 4.0 RC (or you can install it from the repositories).

Uncompress the files:

Rename the folder to mongo4.0 and create the data folder inside of the bin folder:

Start the database process:
Important: in order to have multi-statement transactions replica-set must be enabled

Initialize the replica-set:

Start a session and then a transaction:

Then you can decide whether to commit the transaction or abort it:

If the startTransaction throws the IllegalOperation error, make sure the database is running with replica set.

Transaction isolation level in in MongoDB 4.0: Snapshot Isolation

MongoDB 4.0 implements snapshot isolation for the transactions. The pending uncommitted changes are only visible inside the session context (the session which has started the transaction) and are not visible outside. Here is an example:

Connection 1:

Connection 2: starting second transaction in its own session:

Connection 1: commit

Connection 2: after connection1 commits:

Outside of the session it sees the new values, however inside the opened session it will not see the new values.

Now if we commit the transaction inside connection 2 it will commit as well, and we will have 2 rows now (as there are no conflicts).

Sometimes, however, we may see the transient transaction error when committing or even doing find() inside a session: