MongoDB Distributed Transaction with C# .NET – Guidelines

MongoDB Transaction example MongoDB transaction C aspnet core

Today in this article, we will see how to perform MongoDB Transaction C# .NET with easy examples.

ACID transactions are a key demanding capability for any business-critical transactional system. MongoDB supports multi-document transactions.

With the support of MongoDB Distributed Transaction, transactions can be used across multiple operations, collections, databases, documents, and shards. Today in this article we shall see how to get started with Mongo DB transactions using the C# MongoDB driver.

We shall be following the below steps overall for today’s article,

Getting Started

Create an ASP.NET Core API

Let’s create .NET 5 API. You can very much use other non-host application types like Console if needed.

mongodb Transaction C

Add MongoDB Driver Nuget package

Please add the MongoDB driver NuGet package using the Nuget Package manager.

Using NuGet Package Manager

PM> Install-Package MongoDB.Driver -Version 2.12.4

Configuring MongoDB using Dependency Injection

Below is a sample example of using the DI. One can use the same techniques to inject Mongo Driver instance in any module.

mongodb transactions

For more details on the above approach, please refer to the below article,

Add MongoDB Distributed Transaction to operations

Enabling transaction in MongoDB using C# Mongo Driver involves the below-highlighted steps,

distributed transactions mongodb

Step 1– Start a client Session for defining the Transaction scope

Step 2Starts a transaction

Step 3– Add your multi-document or multi-collection operation

Step 4 Commit a transaction

Above was the sample pattern which we need to use for performing transactions. Let’s see below a real example.

Commit a transaction

Below is a sample code that I have used for my application,

 
     using (var session = await _context._mongoClient.StartSessionAsync())
            {
                // Begin transaction
                session.StartTransaction();

                try
                {
                    //Update the Order collection
                    var update = Builders<Library>.Update.Set("OrderId", order.orderId);
                    var updateBuilder = Builders<Library>.Update;
                    await _orderCollection.UpdateOneAsync(filter, update);

                    //Update Books collection nestet array
                    await _booksCollection.UpdateOneAsync(x => x.userId == order.inputUserId,
                    Builders<Library>.Update.Set("books.$[g].config.$[c].value", order.inputValue),
                    new UpdateOptions
                    {
                        ArrayFilters = new List<ArrayFilterDefinition>
                        {
                       new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("g.book_name", order.inputBookName)),
                       new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("c.key", order.key))
                        }
                    });

                    //All good , lets commit the transaction 
                    await session.CommitTransactionAsync();

                }
                catch (Exception e)
                {
                    Console.WriteLine("Error in MongoDB Transacation: " + e.Message);
                    await session.AbortTransactionAsync();
                }


Above database updates on the multiple collection orderCollection and booksCollection will be committed only at stage 4. i.e when CommitTransactionAsync() gets called.

Error in Transaction

For any error in the transaction operation, please abort the operation by calling AbortTransactionAsync()

          
    await session.AbortTransactionAsync();
      

Additional guidelines :

References:

Summary

ACID transactions are key demanding capabilities for many use cases, especially business-critical transactional systems. With the support of distributed transactions in MongoDB, transactions can be used across multiple operations, collections, databases, documents, and shards and give you the power to design your backend system operations effectively.

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *