• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:9 mins read
You are currently viewing Working with MongoDB Transactions

MongoDB transactions empower to combine several operations into a single atomic unit of work. Any operations contained within a transaction are guaranteed to either be successful or to have no impact, which ensures data consistency and integrity in multi-document operations.

Advertisements

To work with transactions in MongoDB, we need to make sure you are using a replica set or a shared cluster with MongoDB version 4.0 or later. Note that transactions are not available in standalone MongoDB deployments.

1. MongoDB transaction ACID properties

MongoDB transactions uphold the ACID characteristics. Let’s explore each of these properties in the context of MongoDB transactions.

  • Atomicity: MongoDB’s transactions are atomic, which means that if any one of the operations included within a transaction fails, the entire transaction is undone, leaving the database in its initial state.
  • Consistency: MongoDB ensures consistency by enforcing data validation rules, such as schema validation, during transactional operations.
  • Isolation: In MongoDB, transactions provide snapshot isolation, ensuring that every transaction gets an exact snapshot of the data initially. This isolation level avoids unclean devours, non-repeatable reads, and other concurrency-related problems.
  • Durability: When a transaction is committed in MongoDB, the changes are durably written to the storage layer and are replicated across the replica set to ensure data durability.

2. How to perform a transaction on MongoDB

2.1 Create Session

To begin a transaction in MongoDB, you need to create a session. Sessions are used to carry out several activities inside a transaction that are connected to a particular client connection. The following command of the transaction enables us to create a session.


# Create Session
session = db.getMongo().startSession()

On execution, the getMongo() returns the MongoDB server connection object and then start a new session using startSession().

Transactions in MongoDB

2.2 Start Transaction

Use the session object’s startTransaction() method to start a transaction. This sets the session in a transaction state. To begin a transaction within a MongoDB session, issue the following command.


# Starting transaction
session.startTransaction()

Note that the transactional behavior only applies to operations executed within the session. The session starts with the execution of startTransaction() method. Any operations executed before starting the transaction or on separate sessions are not part of the transaction.

2.3 Execute Operations

Now execute multiple read and write operations within the session, and they will be part of the transaction until it is explicitly committed or aborted. We have performed the update operation in the current transaction session, which updates the document of the specified collection with the given value of the field.


# Update Method
db.updateOne({name: '896721'},{$set:{fees:8000}})

The document has been modified with the new value of the field as represented by the output.  

However, our change to the collection will not be seen outside the transaction until committed. There, we can see the collection below same as before. 

Transactions in MongoDB

We can either commit the transaction or abort it after performing the necessary task. Committing the transaction applies all the changes made within the transaction to the database atomically.

2.4 End Transaction

To succesfully end the transaction use the commitTransaction() method of the session object. If you have mulitple operations after starting the transaction, all operations commits to the database with this method.


# End Transactiom
session.commitTransaction()

Let’s view the collection, which is now updated with the new field value of the specified document.

mongodb transaction

Note that this is a single document transaction but you can very easily extend this to multi-document or multi-operation transactions. All you need to do it add more operations between session.startTransaction() and session.commitTransaction().

2.5 Aborting Transaction in MongoDB

We can abort the transaction if we don’t want to alter the collection. Aborting the transaction discards all the changes made within the transaction. To cancel the transaction, apply the given command. Keep that in mind, and we can’t perform an abort operation after the commit operation.


# Aborting transaction
session.abortTransaction()

The session leaves the transaction state whenever the transaction is finished by committing or aborting.

3. Conclusion

In conclusion, we have explored the transaction in MongoDB and provided an example to perform a transaction. Transactions in MongoDB provide a reliable way to ensure data integrity and consistency in complex operations.

MongoDB supports multi-document transactions, which allow you to perform multiple operations on multiple documents within one transaction, ensuring data consistency across multiple documents. MongoDB’s support for transactions was introduced in version 4.0 and is available for replica sets and sharded clusters.