Before version 4.0, MongoDB uses $isolated operator to update multiple documents but it does not provide “all-or-nothing” atomicity for write operations.
MongoDB resolved this issue in version 4.0 and provides the support of Multi-Document transactions. Prior to starting a transaction, a session must be created. A transaction cannot be run outside a session.
At any given time you may have multiple running sessions in the system, but each session may run only a single transaction at a time. You can run transactions in parallel according to how many open sessions you have.
The following mongo shell methods are available for Transactions to Start & Commit or Abort :
How it works?
Below example clearly explains how transactions work in MongoDB. Here we will be implementing transactions by creating two different sessions.
Session 1 :
In this session 1, I am starting a transaction and inserting a document without commiting the transaction.
Session 2 :
Lets find the inserted document.
Now again in the session 1, lets commit the transaction.
Session 2 :
Now, when we find the document, we could see the same data that we have inserted already in session1.
A collection cannot be dropped or created inside a transaction.
It is not possible to read and write into a system.* collection.
An index cannot be created or dropped inside a transaction.
We can’t use transactions on a standalone server, we need to configure it as a replica set.
By default, a transaction that executes for longer than 60 seconds will automatically expire.
A transaction cannot read or write in config, admin, and local databases.
Note: From upcoming MongoDB version(4.2), transaction will get supported in shared cluster as well.