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

Transactions

On this page

  • Overview
  • Causal Consistency
  • 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.

MongoDB enables causal consistency in client sessions. The causal consistency model guarantees that operations within a session run in a causal order. Clients observe results that are consistent with the causal relationships, or the dependencies between operations. For example, if you perform a series of operations where one operation logically depends on the result of another, any subsequent reads reflect the dependent relationship.

The following table describes the guarantees that causally consistent sessions provide:

Guarantee
Description

Read your writes

Read operations reflect the results of preceding write operations.

Monotonic reads

Read operations do not return results that reflect an earlier data state than a preceding read operation.

Monotonic writes

If a write operation must precede other write operations, the driver runs this write operation first.

For example, if you call InsertOne() to insert a document, then call UpdateOne() to modify the inserted document, the driver runs the insert operation first.

Writes follow reads

If a write operation must follow other read operations, the driver runs the read operations first.

For example, if you call Find() to retrieve a document, then call DeleteOne() to delete the retrieved document, the driver runs the find operation first.

In a causally consistent session, MongoDB ensures a causal relationship between the following operations:

  • Read operations that have a ReadConcern.Majority read concern

  • Write operations that have a WriteConcern.WMajority write concern

Tip

To learn more about the concepts mentioned in this section, see the following MongoDB Server manual entries:

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

Bulk Write Operations