Overview
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.
Methods
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 |
|---|---|
| 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) |
| 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 |
| 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 |
| 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
Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationTokenReturn Type: Task <TResult> |
Method | Description |
|---|---|
| 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) |
| 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: CancellationTokenReturn Type: Task |
| 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: CancellationTokenReturn Type: Task |
| 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
Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationTokenReturn Type: Task <TResult> |
Transaction Options
To configure an individual transaction, pass a
TransactionOptions instance to the StartTransaction() or
WithTransaction() method.
The example in this section sets the read concern to
ReadConcern.Majority and the write concern to
WriteConcern.WMajority.
You can configure a TransactionOptions object with the following
properties:
Property | Description |
|---|---|
| Maximum amount of time that a single
commitTransaction command can run. If the commit exceeds
this limit, MongoDB Server returns a MaxTimeMSExpired
error and does not commit the transaction.If you omit this property, MongoDB Server applies the
default transaction runtime limit. Data Type: TimeSpan? |
| Read concern for the transaction. To learn more, see
Read Concern in the MongoDB Server
manual. Data Type: ReadConcern |
| Read preference for the transaction. To learn more, see
Read Preference in the
MongoDB Server manual. Data Type: ReadPreference |
| Write concern for the transaction. To learn more, see
Write Concern in the MongoDB Server
manual. Data Type: WriteConcern |
Example
This example shows how you can create a session, configure transaction options, create a transaction, and insert documents into multiple collections within the transaction through the following steps:
Create a session from the client by using the
StartSession()method.Create a
TransactionOptionsobject to configure the transaction.Use the
StartTransaction()method to start a transaction.Insert documents into the
booksandfilmscollections.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()) { // Configures transaction options var transactionOptions = new TransactionOptions( readConcern: ReadConcern.Majority, writeConcern: WriteConcern.WMajority ); session.StartTransaction(transactionOptions); 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.
Additional Information
To learn more about the concepts mentioned in this guide, see the following pages in the Server manual:
API Documentation
To learn more about any of the types or methods discussed in this guide, see the following API Documentation: