Updated March 8, 2023
Introduction to MongoDB Transactions
MongoDB transactions are provided in version 4.0 of Mongo DB where the transactions are supported even in Multi-document operations to maintain the ACID properties. The transactions are supported even across the sharded clusters and the replications of the documents in the Mongo database. There arise many situations where we need a transaction to maintain the atomicity in the operations where the process consists of multi-collection data or multi-document data which is supported by MongoDB transactions.
In this article, we will have a look at the necessity of the transactions in MongoDB, the ACID properties of the transactions, and have a look at sample examples to demonstrate the use of Mongo DB transactions in your application.
MongoDB Transactions
There are multiple read and write operations being done from and to the Mongo DB database that needs a behavior where all those set of operations should be completed entirely or none of them should be reflected in the database. This integrity of a set of read and write operations is maintained by using transactions.
For example, consider that you are transferring a certain amount from one to another account. If the amount is deducted from one account and not transferred to the other then the data is inconsistent which eventually leads to your application performing in the wrong way. In order to make this transfer of amount consistent and execute the whole process in a whole or nothing format, we can make use of transactions. This means that if there will be an occurrence of any problem while transferring the amount to other account the whole execution till that point of time for that process will be rollbacked.
In this way, consistency and integrity can be maintained while executing multiple operations. The only disadvantage of using the transactions in your application is that there is some extra work to be done while maintaining the transactions which adds to overhead. Also, locking of the resources involved in the transaction creates the waiting period for the user which may affect the user experience.
ACID properties of transactions
All the transactions in Mongo DB follow the properties of ACID which stand for Atomicity, Consistency, Isolation, and durability. It is important for exhibiting all these four characteristics inside your transaction for validation. Let us discuss one by one what all these four properties of ACID stand for –
Atomicity – By this property, we mean that all the operations that are present inside the transaction will together be treated as a single unit which means that the failure of even a single operation will lead to a rollback of all the previously executed operations of that transaction and marking the failure of the transaction. Inversely, if all the operations are executed successfully the transaction is also succeeded.
Consistency – By consistency in the database what we mean is that any changes in data will lead to the satisfaction of all the constraints applied on that column of a field in a database. For example, when a unique key is assigned to the document inside a collection then the field is always kept unique while maintaining its consistency.
Isolation –
Isolation is the property that helps in explaining the segregate execution of each transaction when multiple transactions are running in the system simultaneously.
Durability – Durability means the changes in the data being made in the database persist and are stored in the backing store as well which means is there is any kind of system failure arising then the data won’t be affected and will be stored and maintained properly.
The ACID properties of the transaction make the use of the Mongo DB database reliable for the developers and users. The single document transaction which carries out all the operations of read and write on only a single document in MongoDB is already ACID compliant. If you have structured your database well, you won’t even require a multi-document transaction.
However, when needed it is also possible to maintain the transaction which is multi-document in nature but it usually comes with extra overhead that involves maintaining such transactions. The transactions work across multiple clusters and work in the way that we expect them to while using a multi-document ACID-compliant Mongo DB database. You need to consider the performance overheads that will generate while using such kind of distributed system and keep in mind the available resources and the goals of performance that you have set in your mind.
Working of Transactions
We have to initiate a session in MongoDB with the help of the driver.
Further, you can make use of this session for executing all the operations that you wanted your transaction to carry out. This operation can be having the involvement of multiple documents, collections, and also across sharded clusters and all of them being ACID compliant.
Limitations of using transactions in MongoDB
There are many limitations while using the transactions in MongoDB which are as listed below –
- Read operation cannot be performed on system collections.
- Write operation cannot be done on non-existing collections or capped collections.
- Indexes and collections cannot be modified or dropped in the transactions.
Example
Consider the following example of a transaction in Mongo DB.
Here, we will initiate a new session and then perform the operations of transactions –
sampleSession = db.getMongo().startSession()
sampleSession.startTransaction()
sampleSession.getDatabase("EDUCBA").test.insert({today : new Date()})
sampleSession.getDatabase("EDUCBA").test.insert({Articles : "MongoDB transaction Example"})
console.log("The article was added successfully!.");
sampleSession.commitTransaction()
The output of the execution of the above code snippet is as shown in the below image –
Further, we can decide if we want to commit the transaction or abort it by using the following statements –
sampleSession.commitTransaction()
sampleSession.abortTransaction()
Conclusion
The transactions can be single-document, multi-document, or even involving multiple clusters in it in the case of a distributed system. In Mongo DB the single document transactions are maintained internally. However, in the case of multi-document transactions, there is an extra overhead of managing these transactions. Transactions following the ACID properties make their database consistent, atomic, durable, and isolated. There are multiple methods using which we can initiate the session and abort or commit or transaction in Mongo DB.
Recommended Articles
This is a guide to MongoDB Transactions. Here we discuss the definition, Working of Transactions, examples with code implementation, limitations. You may also have a look at the following articles to learn more –