Skip to content

Commit 7699cfb

Browse files
authored
DOCSP-45214 Add transactions (#115)
1 parent 14e1d51 commit 7699cfb

File tree

2 files changed

+192
-0
lines changed

2 files changed

+192
-0
lines changed

Diff for: source/includes/write/transaction.rb

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
require 'bundler/inline'
2+
gemfile do
3+
source 'https://rubygems.org'
4+
gem 'mongo'
5+
end
6+
7+
uri = "<connection string URI>"
8+
9+
Mongo::Client.new(uri) do |client|
10+
#start-txn
11+
database = client.use('sample_mflix')
12+
movies_collection = database[:movies]
13+
users_collection = database[:users]
14+
15+
def run_transaction(session, movies_collection, users_collection)
16+
transaction_options = {
17+
read_concern: { level: "snapshot" },
18+
write_concern: { w: "majority" }
19+
}
20+
21+
session.with_transaction(transaction_options) do
22+
# Inserts document into the "movies" collection
23+
insert_result = movies_collection.insert_one({ name: 'The Menu', runtime: 107 }, session: session)
24+
puts "Insert completed: #{insert_result.inspect}"
25+
26+
# Updates document in the "users" collection
27+
update_result = users_collection.update_one({ name: 'Amy Phillips'}, { "$set" => { name: 'Amy Ryan' }}, session: session)
28+
puts "Update completed: #{update_result.inspect}"
29+
end
30+
end
31+
32+
# Starts a session
33+
session = client.start_session
34+
35+
begin
36+
# Runs the transaction
37+
run_transaction(session, movies_collection, users_collection)
38+
puts "Transaction committed successfully."
39+
rescue Mongo::Error::OperationFailure => e
40+
puts "Transaction failed and was aborted. Error: #{e.message}"
41+
ensure
42+
session.end_session
43+
end
44+
#end-txn
45+
end

Diff for: source/write/transactions.txt

+147
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
.. _ruby-transactions:
2+
3+
============
4+
Transactions
5+
============
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: code example, ACID compliance, multi-document
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-short+} to perform
24+
**transactions**. Transactions allow you to perform a series of operations that
25+
change data only if the entire transaction is committed. If any operation in the
26+
transaction does not succeed, the driver stops the transaction and discards all
27+
data changes before they ever become visible. This feature is called
28+
**atomicity**.
29+
30+
In MongoDB, transactions run within logical **sessions**. A session is a
31+
grouping of related read or write operations that you want to run sequentially.
32+
Sessions enable causal consistency for a group of operations and allow you to
33+
run operations in an **ACID-compliant** transaction, which is a transaction that
34+
meets an expectation of atomicity, consistency, isolation, and durability.
35+
MongoDB guarantees that the data involved in your transaction operations remains
36+
consistent, even if the operations encounter unexpected errors.
37+
38+
When using the {+driver-short+}, you can start a session by calling the
39+
``start_session`` method on your client. Then, you can perform transactions
40+
within the session.
41+
42+
.. warning::
43+
44+
Use a session only in operations running on the ``Mongo::Client`` that
45+
created it. Using a session with a different ``Mongo::Client`` results in
46+
operation errors.
47+
48+
Methods
49+
-------
50+
51+
After calling the ``start_session`` method to start a session, you can use
52+
methods from the ``Mongo::Session`` class to manage the session state. The
53+
following table describes the methods you can use to manage a transaction:
54+
55+
.. list-table::
56+
:widths: 25 75
57+
:stub-columns: 1
58+
:header-rows: 1
59+
60+
* - Method
61+
- Description
62+
63+
* - ``start_transaction``
64+
- | Starts a new transaction on this session. You cannot start a
65+
transaction if there's already an active transaction running in
66+
the session.
67+
|
68+
| You can set transaction options including read concern, write concern,
69+
and read preference by passing a ``Hash`` as a parameter.
70+
71+
* - ``commit_transaction``
72+
- | Commits the active transaction for this session. This method returns an
73+
error if there is no active transaction for the session, the
74+
transaction was previously ended, or if there is a write conflict.
75+
76+
* - ``abort_transaction``
77+
- | Ends the active transaction for this session. This method returns an
78+
error if there is no active transaction for the session or if the
79+
transaction was committed or ended.
80+
81+
* - ``with_transaction``
82+
- | Starts a transaction prior to calling the supplied block, and commits
83+
the transaction when the block finishes. If any of the operations in
84+
the block, or the commit operation, result in a transient transaction
85+
error, the block and/or the commit will be executed again.
86+
87+
.. _ruby-txn-example:
88+
89+
Transaction Example
90+
-------------------
91+
92+
This example defines a ``run_transaction`` method that modifies data in the
93+
collections of the ``sample_mflix`` database. The code performs the following
94+
actions:
95+
96+
- Creates ``Mongo::Collection`` instances to access the ``movies`` and ``users``
97+
collections.
98+
- Specifies the read and write concerns for the transaction.
99+
- Starts the transaction.
100+
- Inserts a document into the ``movies`` collection and prints the results.
101+
- Updates a document in the ``users`` collection and prints the results.
102+
103+
.. literalinclude:: /includes/write/transaction.rb
104+
:language: ruby
105+
:start-after: start-txn
106+
:end-before: end-txn
107+
:dedent:
108+
:copyable:
109+
110+
.. sharedinclude:: dbx/transactions-parallelism.rst
111+
112+
.. TODO:
113+
Replace content to use this wording when the bulk write guide is added:
114+
.. replacement:: driver-specific-content
115+
.. If you're using {+mdb-server+} v8.0 or later, you can perform
116+
.. write operations on multiple namespaces within a single transaction by using
117+
.. the ``bulk-write`` method. For more information, see the :ref:`<ruby-bulk-write>`
118+
.. guide.
119+
120+
Additional Information
121+
----------------------
122+
123+
To learn more about the concepts mentioned in this guide, see the
124+
following pages in the {+mdb-server+} manual:
125+
126+
- :manual:`Transactions </core/transactions/>`
127+
- :manual:`Server Sessions </reference/server-sessions/>`
128+
- :manual:`Read Isolation, Consistency, and Recency
129+
</core/read-isolation-consistency-recency/>`
130+
131+
To learn more about ACID compliance, see the :website:`A Guide to ACID Properties in Database Management Systems
132+
</basics/acid-transactions>` article on the MongoDB website.
133+
134+
To learn more about insert operations, see the
135+
:ref:`ruby-write-insert` guide.
136+
137+
API Documentation
138+
~~~~~~~~~~~~~~~~~
139+
140+
To learn more about the methods and types mentioned in this
141+
guide, see the following API documentation:
142+
143+
- `Mongo::Session <{+api-root+}/Mongo/Session.html>`_
144+
- `start_transaction <{+api-root+}/Mongo/Session.html#start_transaction-instance_method>`_
145+
- `commit_transaction <{+api-root+}/Mongo/Session.html#commit_transaction-instance_method>`_
146+
- `abort_transaction <{+api-root+}/Mongo/Session.html#abort_transaction-instance_method>`_
147+
- `with_transaction <{+api-root+}/Mongo/Session.html#with_transaction-instance_method>`_

0 commit comments

Comments
 (0)