Performing a multi-document transaction in MongoDB using the C# MongoDB Driver

Views: 1679
Comments: 2
Like/Unlike: 2
Posted On: 08-Jul-2023 04:33 

Share:   fb twitter linkedin
Rahul M...
4916 Points
27 Posts


In MongoDB, a multi-document transaction allows you to perform multiple read and write operations on multiple documents within a single transaction. This ensures the atomicity, consistency, isolation, and durability (ACID) properties of the transaction. 

 

 

To define a multi-document transaction in MongoDB, we need to use the Session object provided by the MongoDB driver. Here's an example of how you can define a multi-document transaction using the C# MongoDB Driver:

 

using MongoDB.Driver;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Create a MongoDB client
        var client = new MongoClient("mongodb://localhost:27017");
        var database = client.GetDatabase("your_database_name");
        var collection1 = database.GetCollection<BsonDocument>("collection1");
        var collection2 = database.GetCollection<BsonDocument>("collection2");

        // Start a session
        using (var session = client.StartSession())
        {
            // Define options for the transaction
            var options = new TransactionOptions(
                readConcern: ReadConcern.Snapshot,
                writeConcern: WriteConcern.WMajority);

            // Start a transaction
            session.StartTransaction(options);

            try
            {
                // Perform operations within the transaction
                var document1 = new BsonDocument("name", "John Doe");
                collection1.InsertOne(session, document1);

                var document2 = new BsonDocument("name", "Jane Smith");
                collection2.InsertOne(session, document2);

                // Commit the transaction
                session.CommitTransaction();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred during the transaction: " + ex.Message);

                // Rollback the transaction
                session.AbortTransaction();
            }
        }
    }
}

 

In this example, we create a MongoDB client and retrieve two collections from a database. We start a session using the StartSession method and define transaction options. Within the transaction, we perform multiple operations, such as inserting documents into collection1 and collection2. If any exception occurs, we roll back the transaction using the AbortTransaction method. Otherwise, we commit the transaction using the CommitTransaction method.

Remember to replace "mongodb://localhost:27017" with the connection string for your MongoDB server, "your_database_name" with the name of your database, "collection1" and "collection2" with the names of your collections.

It's important to note that multi-document transactions have some limitations and performance implications. Therefore, it's recommended to design your data model and operations to minimize the need for multi-document transactions whenever possible.

Also, ensure that your MongoDB server version supports multi-document transactions, as they were introduced in MongoDB version 4.0 and later.

 

2 Comments

great article! thanks.


Remu
18-Apr-2024 at 23:08

I like it. great!


mongo
18-Apr-2024 at 23:09
 Log In to Chat