Mongo.Session.with_transaction
with_transaction
, go back to Mongo.Session module for more information.
Convenient function for running multiple write commands in a transaction.
In case of TransientTransactionError
or UnknownTransactionCommitResult
the function will retry the whole transaction or
the commit of the transaction. You can specify a timeout (:transaction_retry_timeout_s
) to limit the time of repeating.
The default value is 120 seconds. If you don't wait so long, you call with_transaction
with the
option transaction_retry_timeout_s: 10
. In this case after 10 seconds of retrying, the function will return
an error.
Example
alias Mongo.Session
{:ok, ids} = Session.with_transaction(top, fn opts ->
{:ok, %InsertOneResult{:inserted_id => id1}} = Mongo.insert_one(top, "dogs", %{name: "Greta"}, opts)
{:ok, %InsertOneResult{:inserted_id => id2}} = Mongo.insert_one(top, "dogs", %{name: "Waldo"}, opts)
{:ok, %InsertOneResult{:inserted_id => id3}} = Mongo.insert_one(top, "dogs", %{name: "Tom"}, opts)
{:ok, [id1, id2, id3]}
end, transaction_retry_timeout_s: 10)
From the specs:
The callback function may be executed multiple times
The implementation of with_transaction
is based on the original examples for Retry Transactions and
Commit Operation from the MongoDB Manual. As such, the callback may be executed any number of times.
Drivers are free to encourage their users to design idempotent callbacks.