Docs Menu
Docs Home
/ / /
C#/.NET
/

Transactions

On this page

  • Overview
  • Methods
  • Example
  • Additional Information
  • API Documentation

In this guide, you can learn how to use the MongoDB .NET/C# Driver to perform transactions. Transactions allow you to run a series of operations that do not change any data until the transaction is committed. If any operation in the transaction returns an error, the driver cancels the transaction and discards all data changes before they ever become visible.

In MongoDB, transactions run within logical sessions. A session is a grouping of related read or write operations that you intend to run sequentially. Sessions enable causal consistency for a group of operations or allow you to execute operations in an ACID transaction. MongoDB guarantees that the data involved in your transaction operations remains consistent, even if the operations encounter unexpected errors.

When using the .NET/C# Driver, you can create a new session from a MongoClient instance as an IClientSession type. We recommend that you reuse your client for multiple sessions and transactions instead of instantiating a new client each time.

Warning

Use an IClientSession only with the MongoClient (or associated MongoDatabase or MongoCollection) that created it. Using an IClientSession with a different MongoClient results in operation errors.

Create an IClientSession by using either the synchronous StartSession() or the asynchronous StartSessionAsync() method on your MongoClient instance. You can then modify the session state by using the method set provided by the IClientSession interface. Select from the following Synchronous Methods and Asynchronous Methods tabs to learn about the methods to manage your transaction:

Method
Description

StartTransaction()

Starts a new transaction, configured with the given options, on this session. Throws an exception if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions (optional)

AbortTransaction()

Ends the active transaction for this session. Throws an exception if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

Parameter: CancellationToken

CommitTransaction()

Commits the active transaction for this session. Throws an exception if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.

Parameter: CancellationToken

WithTransaction()

Starts a transaction on this session and runs the given callback. To learn more about this method, see the withTransaction() page in the Server manual.

IMPORTANT: When catching exceptions within the callback function used by WithTransaction(), you must rethrow the exception before exiting the try-catch block. Failing to do so can result in an infinite loop. For further details on how to handle exceptions in this case, see Transactions in the Server manual and select C# from the language dropdown to view the example.


Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationToken
Return Type: Task <TResult>
Method
Description

StartTransaction()

Starts a new transaction, configured with the given options, on this session. Throws an exception if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions (optional)

AbortTransactionAsync()

Ends the active transaction for this session. Throws an exception if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

Parameter: CancellationToken
Return Type: Task

CommitTransactionAsync()

Commits the active transaction for this session. Throws an exception if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.

Parameter: CancellationToken
Return Type: Task

WithTransactionAsync()

Starts a transaction on this session and runs the given callback. To learn more about this method, see the withTransaction() page in the Server manual.

IMPORTANT: When catching exceptions within the callback function used by WithTransactionAsync(), you must rethrow the exception before exiting the try-catch block. Failing to do so can result in an infinite loop. For further details on how to handle exceptions in this case, see Transactions in the Server manual and select C# from the language dropdown to view the example.


Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationToken
Return Type: Task <TResult>

This example shows how you can create a session, create a transaction, and insert documents into multiple collections within the transaction through the following steps:

  1. Create a session from the client by using the StartSession() method.

  2. Use the StartTransaction() method to start a transaction.

  3. Insert documents into the books and films collections.

  4. Commit the transaction by using the CommitTransaction() method.

var books = database.GetCollection<Book>("books");
var films = database.GetCollection<Film>("films");
// Begins transaction
using (var session = mongoClient.StartSession())
{
session.StartTransaction();
try
{
// Creates sample data
var book = new Book
{
Title = "Beloved",
Author = "Toni Morrison",
InStock = true
};
var film = new Film
{
Title = "Star Wars",
Director = "George Lucas",
InStock = true
};
// Inserts sample data
books.InsertOne(session, book);
films.InsertOne(session, film);
// Commits our transaction
session.CommitTransaction();
}
catch (Exception e)
{
Console.WriteLine("Error writing to MongoDB: " + e.Message);
return;
}
// Prints a success message if no error thrown
Console.WriteLine("Successfully committed transaction!");
}
Successfully committed transaction!

Note

Parallel Operations Not Supported

The .NET/C# Driver does not support running parallel operations within a single transaction.

If you're using MongoDB Server v8.0 or later, you can perform write operations on multiple namespaces within a single transaction by using the BulkWrite() or BulkWriteAsync() method. For more information, see Bulk Write Operations.

To learn more about the concepts mentioned in this guide, see the following pages in the Server manual:

To learn more about any of the types or methods discussed in this guide, see the following API Documentation:

Back

GUIDs