Skip to content

Commit 8553e6d

Browse files
authored
DOCSP-37469: Add transactions page (#199)
1 parent 2dfb176 commit 8553e6d

File tree

3 files changed

+330
-0
lines changed

3 files changed

+330
-0
lines changed

source/fundamentals.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Fundamentals
2222
/fundamentals/bson
2323
/fundamentals/specify-query
2424
/fundamentals/serialization
25+
/fundamentals/transactions
2526
/fundamentals/logging
2627
/fundamentals/time-series
2728
/fundamentals/encrypt-fields
@@ -37,6 +38,7 @@ Fundamentals
3738
- :ref:`csharp-bson`
3839
- :ref:`csharp-specify-query`
3940
- :ref:`csharp-serialization`
41+
- :ref:`csharp-transactions`
4042
- :ref:`csharp-logging`
4143
- :ref:`csharp-time-series`
4244
- :ref:`Encrypt Fields <csharp-fle>`
Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
.. _csharp-transactions:
2+
3+
============
4+
Transactions
5+
============
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: code example, multi-document
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-long+} to perform
24+
**transactions**. :manual:`Transactions </core/transactions/>` allow
25+
you to run a series of operations that do not change any data until the
26+
transaction is committed. If any operation in the transaction returns an
27+
error, the driver cancels the transaction and discards all data changes
28+
before they ever become visible.
29+
30+
In MongoDB, transactions run within logical **sessions**. A
31+
:manual:`session </reference/server-sessions/>` is a grouping of related
32+
read or write operations that you intend to run sequentially. Sessions
33+
enable :manual:`causal consistency
34+
</core/read-isolation-consistency-recency/#causal-consistency>` for a
35+
group of operations or allow you to execute operations in an
36+
:website:`ACID transaction </basics/acid-transactions>`. MongoDB
37+
guarantees that the data involved in your transaction operations remains
38+
consistent, even if the operations encounter unexpected errors.
39+
40+
When using the {+driver-short+}, you can create a new session from a
41+
``MongoClient`` instance as an ``IClientSession`` type. We recommend that you reuse
42+
your client for multiple sessions and transactions instead of
43+
instantiating a new client each time.
44+
45+
.. warning::
46+
47+
Use an ``IClientSession`` only with the ``MongoClient`` (or associated
48+
``MongoDatabase`` or ``MongoCollection``) that created it. Using an
49+
``IClientSession`` with a different ``MongoClient`` results in operation
50+
errors.
51+
52+
Methods
53+
-------
54+
55+
Create an ``IClientSession`` by using either the synchronous ``StartSession()`` or
56+
the asynchronous ``StartSessionAsync()`` method on your ``MongoClient`` instance.
57+
You can then modify the session state by using the method set
58+
provided by the ``IClientSession`` interface. Select from the following
59+
:guilabel:`Synchronous Methods` and :guilabel:`Asynchronous Methods`
60+
tabs to learn about the methods to manage your transaction:
61+
62+
.. tabs::
63+
64+
.. tab:: Synchronous Methods
65+
:tabid: synchronous-methods
66+
67+
.. list-table::
68+
:widths: 40 60
69+
:header-rows: 1
70+
71+
* - Method
72+
- Description
73+
74+
* - ``StartTransaction()``
75+
- | Starts a new transaction, configured with the given options, on
76+
this session. Throws an exception if there is already
77+
a transaction in progress for the session. To learn more about
78+
this method, see the :manual:`startTransaction() page
79+
</reference/method/Session.startTransaction/>` in the Server manual.
80+
|
81+
| **Parameter**: ``TransactionOptions`` (optional)
82+
83+
* - ``AbortTransaction()``
84+
- | Ends the active transaction for this session. Throws an exception
85+
if there is no active transaction for the session or the
86+
transaction has been committed or ended. To learn more about
87+
this method, see the :manual:`abortTransaction() page
88+
</reference/method/Session.abortTransaction/>` in the Server manual.
89+
|
90+
| **Parameter**: ``CancellationToken``
91+
92+
* - ``CommitTransaction()``
93+
- | Commits the active transaction for this session. Throws an exception
94+
if there is no active transaction for the session or if the
95+
transaction was ended. To learn more about
96+
this method, see the :manual:`commitTransaction() page
97+
</reference/method/Session.commitTransaction/>` in the Server manual.
98+
|
99+
| **Parameter**: ``CancellationToken``
100+
101+
* - ``WithTransaction()``
102+
- | Starts a transaction on this session and runs the given callback. To
103+
learn more about this method, see the :manual:`withTransaction() page
104+
</reference/method/Session.withTransaction/>` in the Server manual.
105+
106+
.. warning:: Handling Exceptions
107+
108+
When catching exceptions within the callback function used by
109+
``WithTransaction()``, you **must** rethrow the exception before
110+
exiting the try-catch block. Failing to do so can result in an
111+
infinite loop. For further details on how to handle exceptions in this
112+
case, see :manual:`Transactions </core/transactions/>` in the Server
113+
manual and select :guilabel:`C#` from the language dropdown to view
114+
the example.
115+
116+
|
117+
| **Parameters**: ``Func <IClientSessionHandle, CancellationToken, Task<TResult>>``, ``TransactionOptions``, ``CancellationToken``
118+
| **Return Type**: ``Task <TResult>``
119+
120+
.. tab:: Asynchronous Methods
121+
:tabid: asynchronous-methods
122+
123+
.. list-table::
124+
:widths: 40 60
125+
:header-rows: 1
126+
127+
* - Method
128+
- Description
129+
130+
* - ``StartTransaction()``
131+
- | Starts a new transaction, configured with the given options, on
132+
this session. Throws an exception if there is already
133+
a transaction in progress for the session. To learn more about
134+
this method, see the :manual:`startTransaction() page
135+
</reference/method/Session.startTransaction/>` in the Server manual.
136+
|
137+
| **Parameter**: ``TransactionOptions`` (optional)
138+
139+
* - ``AbortTransactionAsync()``
140+
- | Ends the active transaction for this session. Throws an exception
141+
if there is no active transaction for the session or the
142+
transaction has been committed or ended. To learn more about
143+
this method, see the :manual:`abortTransaction() page
144+
</reference/method/Session.abortTransaction/>` in the Server manual.
145+
|
146+
| **Parameter**: ``CancellationToken``
147+
| **Return Type**: ``Task``
148+
149+
150+
* - ``CommitTransactionAsync()``
151+
- | Commits the active transaction for this session. Throws an
152+
exception if there is no active transaction for the session or if the
153+
transaction was ended. To learn more about
154+
this method, see the :manual:`commitTransaction() page
155+
</reference/method/Session.commitTransaction/>` in the Server manual.
156+
|
157+
| **Parameter**: ``CancellationToken``
158+
| **Return Type**: ``Task``
159+
160+
* - ``WithTransactionAsync()``
161+
- | Starts a transaction on this session and runs the given callback. To
162+
learn more about this method, see the :manual:`withTransaction() page
163+
</reference/method/Session.withTransaction/>` in the Server manual.
164+
165+
.. warning:: Handling Exceptions
166+
167+
When catching exceptions within the callback function used by
168+
``WithTransactionAsync()``, you **must** rethrow the exception
169+
before exiting the try-catch block. Failing to do so can result in an
170+
infinite loop. For further details on how to handle exceptions in this
171+
case, see :manual:`Transactions </core/transactions/>` in the Server
172+
manual and select :guilabel:`C#` from the language dropdown to view
173+
the example.
174+
175+
|
176+
| **Parameters**: ``Func <IClientSessionHandle, CancellationToken, Task<TResult>>``, ``TransactionOptions``, ``CancellationToken``
177+
| **Return Type**: ``Task <TResult>``
178+
179+
Example
180+
-------
181+
182+
This example shows how you can create a session, create a
183+
transaction, and insert documents into multiple collections within the transaction
184+
through the following steps:
185+
186+
1. Create a session from the client by using the ``StartSession()`` method.
187+
#. Use the ``StartTransaction()`` method to start a transaction.
188+
#. Insert documents into the ``books`` and ``films`` collections.
189+
#. Commit the transaction by using the ``CommitTransaction()`` method.
190+
191+
.. io-code-block::
192+
193+
.. input:: /includes/fundamentals/code-examples/Transaction.cs
194+
:language: csharp
195+
:dedent:
196+
:start-after: begin-transaction
197+
:end-before: end-transaction
198+
199+
.. output::
200+
:language: console
201+
:visible: false
202+
203+
Successfully committed transaction!
204+
205+
Additional Information
206+
----------------------
207+
208+
To learn more about the concepts mentioned in this guide, see the
209+
following pages in the Server manual:
210+
211+
- :manual:`Transactions </core/transactions/>`
212+
- :manual:`Server Sessions </reference/server-sessions/>`
213+
- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>`
214+
215+
API Documentation
216+
~~~~~~~~~~~~~~~~~
217+
218+
To learn more about any of the types or methods discussed in this
219+
guide, see the following API Documentation:
220+
221+
- `IClientSession <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.html>`__
222+
- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__
223+
- `StartTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.StartTransaction.html>`__
224+
- `AbortTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.AbortTransaction.html>`__ / `AbortTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.AbortTransactionAsync.html>`__
225+
- `CommitTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.CommitTransaction.html>`__ / `CommitTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.CommitTransactionAsync.html>`__
226+
- `WithTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.WithTransaction.html>`__ / `WithTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.WithTransactionAsync.html>`__
227+
- `TransactionOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.TransactionOptions.html>`__
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
using MongoDB.Bson;
2+
using MongoDB.Bson.Serialization.Attributes;
3+
using MongoDB.Bson.Serialization.Conventions;
4+
using MongoDB.Driver;
5+
6+
public class BookTransaction
7+
{
8+
// Replace with your connection string
9+
private const string MongoConnectionString = "<YOUR_CONNECTION_STRING>";
10+
11+
public static void Main(string[] args)
12+
{
13+
// Establishes the connection to MongoDB and accesses the library database
14+
var mongoClient = new MongoClient(MongoConnectionString);
15+
var database = mongoClient.GetDatabase("library");
16+
17+
// Cleans up the collections we'll be using
18+
Setup(database);
19+
20+
// begin-transaction
21+
var books = database.GetCollection<Book>("books");
22+
var films = database.GetCollection<Film>("films");
23+
24+
// Begins transaction
25+
using (var session = mongoClient.StartSession())
26+
{
27+
session.StartTransaction();
28+
29+
try
30+
{
31+
// Creates sample data
32+
var book = new Book
33+
{
34+
Title = "Beloved",
35+
Author = "Toni Morrison",
36+
InStock = true
37+
};
38+
39+
var film = new Film
40+
{
41+
Title = "Star Wars",
42+
Director = "George Lucas",
43+
InStock = true
44+
};
45+
46+
// Inserts sample data
47+
books.InsertOne(session, book);
48+
films.InsertOne(session, film);
49+
50+
// Commits our transaction
51+
session.CommitTransaction();
52+
}
53+
catch (Exception e)
54+
{
55+
Console.WriteLine("Error writing to MongoDB: " + e.Message);
56+
return;
57+
}
58+
59+
// Prints a success message if no error thrown
60+
Console.WriteLine("Successfully committed transaction!");
61+
}
62+
// end-transaction
63+
}
64+
65+
public static void Setup(IMongoDatabase database)
66+
{
67+
database.DropCollection("books");
68+
database.CreateCollection("books");
69+
70+
database.DropCollection("films");
71+
database.CreateCollection("films");
72+
}
73+
}
74+
75+
public class Book
76+
{
77+
public ObjectId Id { get; set; }
78+
79+
[BsonElement("title")]
80+
public string Title { get; set; }
81+
82+
[BsonElement("author")]
83+
public string Author { get; set; }
84+
85+
[BsonElement("inStock")]
86+
public bool InStock { get; set; }
87+
}
88+
89+
public class Film
90+
{
91+
public ObjectId Id { get; set; }
92+
93+
[BsonElement("title")]
94+
public string Title { get; set; }
95+
96+
[BsonElement("director")]
97+
public string Director { get; set; }
98+
99+
[BsonElement("inStock")]
100+
public bool InStock { get; set; }
101+
}

0 commit comments

Comments
 (0)