Open In App

Transactions in MongoDB

Last Updated : 01 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Transactions in MongoDB allow merging groups of operations as a single atomic unit. They provide atomicity, consistency, isolation, and durability (ACID) properties to ensure that complex operations can be safely and reliably performed.

It is an important attribute for maintaining data consistency when working on large projects.

In this article, we will learn about transactions in MongoDB including what they involve, advantages as well as disadvantages associated with them, implementation, and other related concerns.

What are ACID Transactions in MongoDB?

An ACID transaction is a group of operations that are merged into one single operation. These operations are run sequentially in an all-or-nothing format. This means that all operations in a transaction should be executed successfully, for a transaction to be executed. If even a single operation fails to be executed, the transaction will be aborted.

For example, suppose you run an e-commerce store. An order process contains several steps:

  • Reducing Stock Quantity
  • Creating an order record
  • Charging customer with the correct amount

if any of these steps fail, the entire transaction of order will fail and roll back. This MongoDB transaction example show the working of transactions.

The term ACID means (atomicity, consistency, isolation, and durability). ACID transactions ensure data integrity and consistency in MongoDB. They are used across multiple operations, collections, databases, documents, and shards, and they are atomic, treating all data changes as a single unit of work.

MongoDB supports multi-document ACID transactions and distributed multi-document ACID transactions.

Features of Transactions in MongoDB

Transactions allow developers in MongoDB to treat a set of operations as one atomic unit, where if none will fail only then transaction is successful. Data consistency can be achieved during synchronization among different documents/collections with this characteristic. It provides end-to-end support for multi-document transactions across multiple collections and databases.

They are typically used in applications where values are exchanged between different parties, such as “System of Record” or “Line of Business” applications, and are particularly beneficial in systems that move funds around like banking applications or supply chain or shipping systems where ownership of a good is transferred, or in e-commerce.

MongoDB provides two APIs to use transactions: the core API and the callback API. The core API requires an explicit call to start and to commit the transaction, while the callback API starts a transaction, executes the specified operations, and commits (or aborts on error) automatically.

To create a transaction session, you can use the MongoDB shell to start a transaction and perform operations within the transaction. If a transactions session runs for more than 60 seconds after the initial startTransaction() method, MongoDB will automatically abort the operation.

Benefits of Transactions in MongoDB

There are four properties of MongoDB database transaction, that ensures data validity despite interruptions and errors. They are: atomicity, consistency, isolation and durability.

Let’s understand these benefits in detail below:

  • Atomicity: This ensures that a transaction is handled as a single, indivisible unit of work. It means either all of the operations of transactions succeed or none of them will execute. This prevents situations where just a few operations are completed, inconsistently leaving the machine.
  • Consistency: Transactions assist in maintaining the consistency of a database by way of ensuring that only genuine data is written into the database. If a transaction is completed that violates the database’s consistency guidelines, the whole transaction might be rolled returned and the database will continue to be unchanged.
  • Isolation: This property guarantees that the concurrent execution of transactions leaves the database inside the same state that would have been received if the transactions were done sequentially. It gives a mechanism to cover the intermediate states of a transaction from other simultaneously achieved transactions.
  • Durability: Once a transaction has been dedicated, its effects are permanent inside the database. This remains true even in case of system failure. This belonging ensures that after a transaction completes successfully, the modifications it has made to the database persist and aren’t misplaced because of any failures.

Disadvantages of Transactions

Transaction also come with certain drawbacks. Some disadvantages of Transactions in MongoDB are listed below:

  • Performance Impact: Transactions can introduce some overall performance overhead, mainly in write-intensive situations, because of the want for locks and coordination.
  • Complexity: Implementing and handling transactions in MongoDB may be complex, mainly for developers surprised by the nuances of allotted systems.

Implementation of Transactions in MongoDB

After learning all the concepts of Transactions, let’s see how to use transactions in MongoDB. We will look at the step by step guide, along with queries of Transaction implementation in MongoDB.

Implementing transactions in MongoDB includes the usage of the startSession, withTransaction, and commitTransaction strategies. Below is a simple example in Python using the PyMongo driver.

Python
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
database = client["your_database"]

with client.start_session() as session:
    session.start_transaction()
    try:
        # Perform operations within the transaction
        database.collection1.insert_one({"key": "value"}, session=session)
        database.collection2.update_one({"key": "old_value"}, {"$set": {"key": "new_value"}}, session=session)

        # Commit the transaction
        session.commit_transaction()
    except Exception as e:
        # Abort the transaction in case of an error
        print("An error occurred:", e)
        session.abort_transaction()

Explanation: This Python code uses PyMongo to perform a transaction in MongoDB, inserting a document into “collection1” and updating a document in “collection2.” If any operation fails, the transaction is aborted.

  • Start_session(): This is a technique in PyMongo that begins a brand new session for executing transactions. A session is a context wherein data is read and written. It may used to execute a couple of operations, both read or write, inside a single transaction.
  • Start_transaction(): This is a technique that starts offevolved a brand new transaction inside a consultation. All the operations finished inside this transaction will follow the ACID Properties. If any operation fails, the transaction can be aborted, and all changes made in the transaction will be rolledback.
  • Commit_transaction(): This technique is used for all modifications made within a transaction to the database. Once a transaction is dedicated, all adjustments are permanent and visible to different sessions.
  • Abort_transaction(): If an error occurs throughout the execution of a transaction, this approach can be used to abort the transaction. Aborting a transaction will roll back all modifications made inside the transaction, leaving the database in its unique form before the transaction start.
  • WithTransaction: This is a utility feature provided by using MongoDB drivers that starts a brand new consultation, executes a given feature (which contains the operations to be performed within the transaction), and automatically commits or aborts the transaction based totally on whether or not the performed efficiently or threw an exception. This simplifies transaction managing by means of abstracting the boilerplate code for starting, committing, and aborting transactions.

Output: This code starts a consultation and a transaction inside that session. It inserts a report into `collection1` and modifies a document in `collection2`. If any operation does not succeed, then it cancels the transaction, and if all operations are positive, then it finalizes the transaction.

Note: Please rename `"your_database"`, `"collection1"`, and `"collection2"` with the genuine names of your
database and collections. Also, interchange `"key": "cost"`, `"key": "old_value"`, and `"key": "new_value" along
with your genuine keys and values.

Conclusion

Transactions in MongoDB mark a considerable step towards information integrity in complicated programs. While their implementation may introduce a few complexities and performance considerations, the benefits of atomicity, consistency, isolation, and durability lead them to be integral for statistics accuracy.

With transactions, MongoDB continues to reinforce its position as a versatile and scalable database solution for modern applications with the help of Transactions Concepts. In this article we have covered the basic concepts of ACID transactions and learnt how to use transactions in MongoDB.

Transaction in MongoDB – Frequently Asked Questions

Does MongoDB have ACID transactions?

Yes, MongoDB has ACID transactions. Starting from version 4.0, MongoDB provides multi-document ACID transactions, ensuring atomicity, consistency, isolation, and durability for transactions across multiple collections and databases.

What is the disadvantage of MongoDB transactions?

Transactions in MongoDB are not well developed as compared to other databases, which can be difficult for applications that need complex transactions and string gurantees.

Why use transactions in MongoDB?

Transactions in MongoDB are useful for ensuring atomicity, consistency, isolation, and durability (ACID) for operations across multiple documents, collections, databases, and shards.

Can you use MongoDB transactions in Node.js?

Yes, you can use MongoDB transactions in Node.js

What is the time limit for a transaction in MongoDB?

MongoDB transactions have a default runtime limit of 60 seconds, after which they will be automatically aborted. But this limit can be changed using the transactionLifetimeLimitSeconds parameter on the server.

Does MongoDB have rollback?

MongoDB does not have a rollback feature, but it can revert write operations on a former primary when it rejoins its replica set after a failover.

What are the best practices for MongoDB transactions?

Best practices for MongoDB transactions include:

  • Breaking long-running transactions into smaller parts
  • Ensuring operations use indexes for quick execution
  • Limiting each transaction to 1,000 document modifications
  • Configuring appropriate read and write concerns
  • Implementing error handling for transaction failures
  • Being aware of the performance cost for transactions affecting multiple shards.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads