-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathtransactions.txt
263 lines (201 loc) · 11 KB
/
transactions.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
.. _csharp-transactions:
============
Transactions
============
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: code example, multi-document
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
In this guide, you can learn how to use the {+driver-long+} to perform
**transactions**. :manual:`Transactions </core/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
:manual:`session </reference/server-sessions/>` is a grouping of related
read or write operations that you intend to run sequentially. Sessions
enable :manual:`causal consistency
</core/read-isolation-consistency-recency/#causal-consistency>` for a
group of operations or allow you to execute operations in an
:website:`ACID transaction </basics/acid-transactions>`. MongoDB
guarantees that the data involved in your transaction operations remains
consistent, even if the operations encounter unexpected errors.
When using the {+driver-short+}, 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.
Causal Consistency
~~~~~~~~~~~~~~~~~~
.. sharedinclude:: dbx/causal-consistency.rst
.. replacement:: insert-one-method
``InsertOne()``
.. replacement:: update-one-method
``UpdateOne()``
.. replacement:: find-one-method
``Find()``
.. replacement:: delete-one-method
``DeleteOne()``
.. replacement:: majority-rc
``ReadConcern.Majority``
.. replacement:: majority-wc
``WriteConcern.WMajority``
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
:guilabel:`Synchronous Methods` and :guilabel:`Asynchronous Methods`
tabs to learn about the methods to manage your transaction:
.. tabs::
.. tab:: Synchronous Methods
:tabid: synchronous-methods
.. list-table::
:widths: 40 60
:header-rows: 1
* - 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 :manual:`startTransaction() page
</reference/method/Session.startTransaction/>` 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 :manual:`abortTransaction() page
</reference/method/Session.abortTransaction/>` 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 :manual:`commitTransaction() page
</reference/method/Session.commitTransaction/>` 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 :manual:`withTransaction() page
</reference/method/Session.withTransaction/>` in the Server manual.
:gold:`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 :manual:`Transactions </core/transactions/>` in the Server
manual and select :guilabel:`C#` from the language dropdown to view
the example.
|
| **Parameters**: ``Func <IClientSessionHandle, CancellationToken, Task<TResult>>``, ``TransactionOptions``, ``CancellationToken``
| **Return Type**: ``Task <TResult>``
.. tab:: Asynchronous Methods
:tabid: asynchronous-methods
.. list-table::
:widths: 40 60
:header-rows: 1
* - 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 :manual:`startTransaction() page
</reference/method/Session.startTransaction/>` 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 :manual:`abortTransaction() page
</reference/method/Session.abortTransaction/>` 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 :manual:`commitTransaction() page
</reference/method/Session.commitTransaction/>` 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 :manual:`withTransaction() page
</reference/method/Session.withTransaction/>` in the Server manual.
:gold:`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 :manual:`Transactions </core/transactions/>` in the Server
manual and select :guilabel:`C#` from the language dropdown to view
the example.
|
| **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:
1. Create a session from the client by using the ``StartSession()`` method.
#. Use the ``StartTransaction()`` method to start a transaction.
#. Insert documents into the ``books`` and ``films`` collections.
#. Commit the transaction by using the ``CommitTransaction()`` method.
.. io-code-block::
.. input:: /includes/fundamentals/code-examples/Transaction.cs
:language: csharp
:dedent:
:start-after: begin-transaction
:end-before: end-transaction
.. output::
:language: console
:visible: false
Successfully committed transaction!
.. sharedinclude:: dbx/transactions-parallelism.rst
.. replacement:: driver-specific-content
If you're using {+mdb-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 :ref:`<csharp-bulk-write>`.
Additional Information
----------------------
To learn more about the concepts mentioned in this guide, see the
following pages in the Server manual:
- :manual:`Transactions </core/transactions/>`
- :manual:`Server Sessions </reference/server-sessions/>`
- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>`
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the types or methods discussed in this
guide, see the following API Documentation:
- `IClientSession <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.html>`__
- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__
- `StartTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.StartTransaction.html>`__
- `AbortTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.AbortTransaction.html>`__ / `AbortTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.AbortTransactionAsync.html>`__
- `CommitTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.CommitTransaction.html>`__ / `CommitTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.CommitTransactionAsync.html>`__
- `WithTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.WithTransaction.html>`__ / `WithTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.WithTransactionAsync.html>`__
- `TransactionOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.TransactionOptions.html>`__
- `CausalConsistency <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientSessionOptions.CausalConsistency.html>`__