Skip to content

Commit 6ab7cf9

Browse files
authored
Merge pull request #119 from gmiller-mdb/DOCSP-45184-ruby-replica-sets
DOCSP-45184-ruby-replica-sets
2 parents 5c616c0 + 3c79f91 commit 6ab7cf9

File tree

3 files changed

+322
-5
lines changed

3 files changed

+322
-5
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
require 'bundler/inline'
2+
3+
gemfile do
4+
source 'https://rubygems.org'
5+
gem 'mongo'
6+
end
7+
8+
uri = '<connection string>'
9+
10+
Mongo::Client.new(uri) do |client|
11+
# Access the database and collection
12+
13+
# start-write-concern
14+
client = Mongo::Client.new(['IP_ADDRESS_001:27017'], database: 'myDB')
15+
myDB = client.database
16+
myCollection = myDB[:myCollection]
17+
18+
myCollection.insert_one(
19+
{ name: 'anotherDocumentName' },
20+
write: {
21+
w: 2,
22+
wtimeout: 5000
23+
}
24+
)
25+
# end-write-concern
26+
27+
# start-write-concern-2
28+
myDoc = { name: 'New Document' }
29+
new_write_concern = Mongo::WriteConcern.get(myDB.write_concern)
30+
myDB[:myCollection].with(write: new_write_concern).insert_one(myDoc)
31+
# end-write-concern-2
32+
33+
# start-read-concern
34+
pipeline = [
35+
{ "$match" => { category: 'KITCHENWARE' } },
36+
{ "$unset" => ['_id', 'category'] }
37+
]
38+
result = myCollection.aggregate(pipeline,
39+
read: { read_concern: { level: :available } })
40+
# end-read-concern
41+
42+
# start-change-read-concern
43+
client = Mongo::Client.new(['IP_ADDRESS_001:27017'],
44+
database: 'mydb',
45+
read_concern: { level: :local })
46+
myDB = client.database
47+
# end-change-read-concern
48+
49+
# start-read-preference
50+
transaction_options = {
51+
read: { mode: :primary },
52+
read_concern: { level: :local },
53+
write_concern: { w: :majority }
54+
}
55+
session = client.start_session
56+
session.start_transaction(transaction_options)
57+
session.commit_transaction
58+
# ...
59+
rescue => e
60+
session.abort_transaction
61+
puts "Transaction aborted due to an error: #{e.message}"
62+
ensure
63+
session.end_session
64+
end
65+
# end-read-preference
66+
67+
# start-read-preference-cluster
68+
uri = 'mongodb+srv://<user>:<password>@<cluster-url>'
69+
options = {
70+
read: {
71+
mode: :secondary,
72+
max_staleness: 120
73+
}
74+
}
75+
client = Mongo::Client.new(uri, options)
76+
myDB = client.database
77+
# end-read-preference-cluster
78+
end
79+
80+
81+

source/index.txt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
Connect </connect>
1717
Write Data </write>
1818
Read Data </read>
19+
Operations on Replica Sets </read-write-pref>
1920
Indexes </indexes>
2021
View the Source <https://github.com/mongodb/mongo-ruby-driver>
2122
API Documentation <{+api-root+}>
@@ -25,7 +26,6 @@
2526

2627
.. TODO:
2728
Write Data </write>
28-
Operations on Replica Sets </read-write-pref>
2929
Monitor Your Application </monitoring>
3030
Data Aggregation </aggregation>
3131
Security </security>
@@ -66,11 +66,11 @@ Learn how to use the {+driver-short+} to work with MongoDB databases and collect
6666

6767
.. Learn how you can write data to MongoDB in the :ref:`ruby-write` section.
6868

69-
.. Configure Operations on Replica Sets
70-
.. ------------------------------------
69+
Configure Operations on Replica Sets
70+
------------------------------------
7171

72-
.. Learn how to configure read and write operations on a replica set in the
73-
.. :ref:`ruby-read-write-pref` section.
72+
Learn how to configure read and write operations on a replica set in the
73+
:ref:`ruby-crud-write-read-pref` section.
7474

7575
.. Optimize Queries by Using Indexes
7676
.. ---------------------------------

source/read-write-pref.txt

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
.. _ruby-crud-write-read-pref:
2+
3+
===============================
4+
CRUD Operations on Replica Sets
5+
===============================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: ruby, customize, preferences, replica set, consistency
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 **write concern**, **read concern**, and
24+
**read preference** configurations to modify the way that MongoDB runs
25+
create, read, update, and delete (CRUD) operations on replica sets.
26+
27+
You can set write concern, read concern, and read preference options at the following
28+
levels:
29+
30+
- Client, which sets the *default for all operation executions* unless overridden
31+
- Session
32+
- Transaction
33+
- Database
34+
- Collection
35+
36+
The preceding list also indicates the increasing order of precedence of the option
37+
settings. For example, if you set a read concern level for a transaction, it will
38+
override a read concern level set for the client.
39+
40+
These options allow you to customize the causal consistency and availability of the data
41+
in your replica sets.
42+
43+
Write Concern
44+
-------------
45+
46+
The write concern specifies the level of acknowledgement requested from MongoDB for
47+
write operations, such as an insert or update, before the operation successfully returns.
48+
Operations that do not specify an explicit write concern inherit the global default write
49+
concern settings.
50+
51+
For more information, see :manual:`Write Concern </reference/write-concern/>` in the
52+
{+mdb-server+} manual. For detailed API documentation, see the `Write Concern API documentation
53+
<{+api-root+}/Mongo/Client.html#write_concern-instance_method>`__.
54+
55+
The following table describes the ``write_concern`` parameters:
56+
57+
.. list-table::
58+
:header-rows: 1
59+
:widths: 25 25 50
60+
61+
* - Parameter
62+
- Type
63+
- Description
64+
65+
* - ``w`` *(optional)*
66+
- integer or string
67+
- Requests acknowledgment that the write operation has propagated to a specified
68+
number of ``mongod`` instances or to ``mongod`` instances that are labelled
69+
with specified tags.
70+
71+
* - ``wtimeoutMS`` *(optional)*
72+
- integer
73+
- Specifies a time limit to prevent write operations from blocking indefinitely.
74+
75+
* - ``journal`` *(optional)*
76+
- boolean
77+
- Requests acknowledgment that the write operation has been written to the
78+
on-disk journal.
79+
80+
Example: Set the Write Concern for a Single Write Operation
81+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
82+
83+
The following code creates a new document and specifies the ``w`` and ``wtimeout``
84+
write concern settings:
85+
86+
.. literalinclude:: /includes/usage-examples/read-write-pref.rb
87+
:language: ruby
88+
:dedent:
89+
:start-after: start-write-concern
90+
:end-before: end-write-concern
91+
92+
Example: Retrieve and Apply an Existing Write Concern
93+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94+
95+
The following code uses the ``new_write_concern`` method to construct a ``write_concern``
96+
from the options of an existing database reference, ``myDB``. Then the new
97+
write concern is applied to an inserted document.
98+
99+
.. literalinclude:: /includes/usage-examples/read-write-pref.rb
100+
:language: ruby
101+
:dedent:
102+
:start-after: start-write-concern-2
103+
:end-before: end-write-concern-2
104+
105+
.. note::
106+
107+
``myDB`` can be replaced with a reference to any entity that accepts a write concern option.
108+
109+
Read Concern
110+
------------
111+
112+
The read concern specifies the following behaviors:
113+
114+
- Level of :manual:`causal consistency </core/causal-consistency-read-write-concerns/>`
115+
across replica sets
116+
117+
- :manual:`Isolation guarantees </core/read-isolation-consistency-recency/>`
118+
maintained during a query
119+
120+
You can specify the read concern setting by using the ``level`` parameter. The default
121+
read concern level is ``local``. This means that the client returns the data from the
122+
replica set member that the client is connected to, with no guarantee that the data has
123+
been written to all replica set members.
124+
125+
.. note::
126+
127+
Lower read concern level requirements may reduce latency.
128+
129+
For more information about read concerns or read concern levels, see
130+
:manual:`Read Concern </reference/read-concern/>` in the {+mdb-server+} manual. For more
131+
detail on the ``read_concern`` type and definitions of the read concern levels, see
132+
`Read Concern <{+api-root+}/Mongo/Client.html#read_concern-instance_method>`__
133+
in the API documentation.
134+
135+
Example: Set the Read Concern Level of an Aggregation
136+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
137+
138+
The following code sets the read concern level of an aggregation to ``"available"``:
139+
140+
.. literalinclude:: /includes/usage-examples/read-write-pref.rb
141+
:language: ruby
142+
:dedent:
143+
:start-after: start-read-concern
144+
:end-before: end-read-concern
145+
146+
.. TODO: insert :ref:`Aggregation <ruby-aggregation>` link here
147+
.. For more information about aggregation, see the Aggregation page.
148+
149+
Example: Change the Read Concern of a Database
150+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
151+
152+
The following code changes the read concern level of a database to ``"local"``:
153+
154+
.. literalinclude:: /includes/usage-examples/read-write-pref.rb
155+
:language: ruby
156+
:dedent:
157+
:start-after: start-change-read-concern
158+
:end-before: end-change-read-concern
159+
160+
Read Preference
161+
---------------
162+
163+
The read preference determines which member of a replica set MongoDB reads when running a
164+
query.
165+
166+
For more detailed API documentation, see the `Read Preference API
167+
documentation <{+api-root+}/Mongo/Collection/View/Readable.html#read_preference-instance_method>`__.
168+
169+
The following table shows options you can use to customize how the server evaluates
170+
members:
171+
172+
.. list-table::
173+
:widths: 25 25 50
174+
:header-rows: 1
175+
176+
* - Parameter
177+
- Type
178+
- Description
179+
180+
* - ``mode``
181+
- ``Symbol``
182+
- Specifies a requirement or preference for which replica set
183+
member the server reads from. The default mode, ``:primary``, specifies that
184+
operations read from the primary member of the replica set.
185+
186+
* - ``tags`` *(optional)*
187+
- ``Array<Hash>``
188+
- Assigns tags to secondary replica set members to customize how the server evaluates
189+
them. Tags cannot be used with the ``:primary`` read preference mode setting.
190+
191+
* - ``options`` *(optional)*
192+
- ``Hash``
193+
- Sets various options, including :manual:`hedge </core/read-preference-hedge-option/>`
194+
and :manual:`maxStalenessSeconds </core/read-preference-staleness/>` that can be
195+
applied to your read preference.
196+
197+
Example: Set Read Preference and Concerns for a Transaction
198+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
199+
200+
The following code sets the read preference, read concern, and write concern for
201+
the operations in a transaction:
202+
203+
.. literalinclude:: /includes/usage-examples/read-write-pref.rb
204+
:language: ruby
205+
:dedent:
206+
:start-after: start-read-preference
207+
:end-before: end-read-preference
208+
209+
.. TODO: insert :ref:`Transactions <ruby-transactions>` link
210+
.. For more information about transactions, see the Transactions guide.
211+
212+
Example: Set the Read Preference of a Cluster in the Connection String
213+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214+
215+
This code example creates a ``MongoClient`` that uses the ``secondary`` read
216+
preference mode when performing queries on a cluster:
217+
218+
.. literalinclude:: /includes/usage-examples/read-write-pref.rb
219+
:language: ruby
220+
:dedent:
221+
:start-after: start-read-preference-cluster
222+
:end-before: end-read-preference-cluster
223+
224+
The preceding example also sets the ``maxStalenessSeconds`` option to ``120``.
225+
For more information about connection string options, see the :manual:`Connection String Options </reference/connection-string/#connection-string-options>`
226+
section in the {+mdb-server+} manual.
227+
228+
API Documentation
229+
-----------------
230+
231+
To learn more about the methods and types mentioned in this guide, see the following API
232+
documentation:
233+
234+
- `Write Concern <{+api-root+}/Mongo/Client.html#write_concern-instance_method>`__
235+
- `Read Concern <{+api-root+}/Mongo/Client.html#read_concern-instance_method>`__
236+
- `Read Preference <{+api-root+}/Mongo/Collection/View/Readable.html#read_preference-instance_method>`__

0 commit comments

Comments
 (0)