You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Since MongoDB 4.x, transactions for multiple write operations are possible. The [Mongo.Session](https://hexdocs.pm/mongodb_driver/Mongo.Session.html#content) is responsible for the details and you can use a convenient api for transactions:
Copy file name to clipboardExpand all lines: lib/mongo/session.ex
+79-17Lines changed: 79 additions & 17 deletions
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,48 @@
1
1
defmoduleMongo.Sessiondo
2
2
3
3
@moduledoc"""
4
+
This module implements the details of the transactions api ([see specs](https://github.com/mongodb/specifications/blob/master/source/transactions/transactions.rst#committransaction)).
5
+
It uses the `:gen_statem` behaviour ([A nice tutorial](https://andrealeopardi.com/posts/connection-managers-with-gen_statem/)) to manage the different states.
4
6
5
-
For gen_statem look here
6
-
* see https://github.com/mongodb/specifications/blob/master/source/transactions/transactions.rst#committransaction
7
-
* see https://andrealeopardi.com/posts/connection-managers-with-gen_statem/
7
+
In case of MongoDB 3.6 or greater the driver uses sessions for each operation. If no session is created the driver will create a so-called implict session. A session is a UUID-Number which
8
+
is added to some operations. The sessions are used to manage the transaction state as well. In most situation you need not to create a session instance, so the interface of the driver is not changed.
9
+
10
+
In case of multiple insert statemantes you can use transaction (MongoDB 4.x) to be sure that all operations are grouped like a single operation. Prerequisites for transactions are:
11
+
MongoDB 4.x must be used as replica set or cluster deployment. The collection used in the operations must already exist. Some operation are not allowed (For example: create index or call count).
First you start a explicit session and a transactions. Use need to use the session for each insert statement as an options with key `:session` otherwise the insert statement won't be
28
+
executed in the transaction. After that you commit the transaction and end the session by calling `end_session`.
29
+
30
+
## Convenient API for Transactions
31
+
32
+
This method is responsible for starting a transaction, invoking a callback, and committing a transaction.
33
+
The callback is expected to execute one or more operations with the transaction; however, that is not enforced.
34
+
The callback is allowed to execute other operations not associated with the transaction.
0 commit comments