Batch Operations in Transactions
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.
MongoDB guarantees that the data involved in your transaction operations remains consistent, even if the operations encounter unexpected errors.
Sessions
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.
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.
The following example shows how to create a session by calling the StartSession()
method:
var client = new MongoClient("mongodb://localhost:27017"); var session = client.StartSession();
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.
ClientSessionOptions
You can customize the behavior of your session by passing an instance of the
ClientSessionOptions
class to the StartSession()
method. The following table
describes the properties that you can set on a ClientSessionOptions
object:
Property | Description |
---|---|
| Specifies whether the session is causally consistent. In a causally consistent session,
the driver executes operations in the order they were issued. To learn more, see
Causal Consistency. Data Type: boolean Default: true |
| Specifies the default transaction options for the session. This includes the maximum commit
time, read concern, read preference, and write concern. Data Type: TransactionOptions Default: null |
| Specifies whether the driver performs snapshot reads. To learn more about snapshot
reads, see Read Concern "snapshot"
in the MongoDB Server manual. Data Type: boolean Default: false |
The following code example shows how to create a session with custom options:
var client = new MongoClient("mongodb://localhost:27017"); var sessionOptions = new ClientSessionOptions { CausalConsistency = true, DefaultTransactionOptions = new TransactionOptions( readConcern: ReadConcern.Available, writeConcern: WriteConcern.Acknowledged) }; var session = client.StartSession(sessionOptions);
Causal Consistency
MongoDB enables causal consistency in certain client sessions. The causal consistency model guarantees that in a distributed system, 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.
To guarantee causal consistency, client sessions must fulfill the following requirements:
When starting a session, the driver must enable the causal consistency option. This option is enabled by default.
Operations must run in a single session on a single thread. Otherwise, the sessions or threads must communicate the operation time and cluster time values to each other. To view an example of two sessions that communicate these values, see the Causal Consistency examples in the MongoDB Server manual.
You must use a
ReadConcern.Majority
read concern.You must use a
WriteConcern.WMajority
write concern. This is the default write concern value.
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 server runs this write operation first. For example, if you call |
Writes follow reads | If a write operation must follow other read operations, the server runs the read operations first. For example, if you call |
Tip
To learn more about the concepts mentioned in this section, see the following MongoDB Server manual entries:
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 , CancellationToken Return 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: CancellationToken Return 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: CancellationToken Return 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 , CancellationToken Return Type: Task <TResult> |
Example
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:
Create a session from the client by using the
StartSession()
method.Use the
StartTransaction()
method to start a transaction.Insert documents into the
books
andfilms
collections.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.
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: