@@ -8,4 +8,333 @@ Configure CRUD Operations
8
8
:local:
9
9
:backlinks: none
10
10
:depth: 2
11
- :class: singlecol
11
+ :class: singlecol
12
+
13
+ .. facet::
14
+ :name: genre
15
+ :values: reference
16
+
17
+ .. meta::
18
+ :keywords: customize, preferences, replica set, consistency, kotlin
19
+
20
+ Overview
21
+ --------
22
+
23
+ In this guide, you can learn how to configure **write concern**, **read concern**,
24
+ and **read preference** options to modify the way that the {+driver-short+} runs
25
+ read and write operations on replica sets.
26
+
27
+ Read and Write Settings Precedence
28
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
29
+
30
+ You can set write concern, read concern, and read preference options at the following
31
+ levels:
32
+
33
+ - Client, which sets the *default for all operation executions* unless overridden
34
+ - Transaction
35
+ - Database
36
+ - Collection
37
+
38
+ This list also indicates the increasing order of precedence of the option settings. For
39
+ example, if you set a read concern for a transaction, it will override the read
40
+ concern settings inherited from the client.
41
+
42
+ Write concern, read concern, and read preference options allow you to customize the
43
+ causal consistency and availability of the data in your replica sets. To see a full
44
+ list of these options, see the following guides in the {+mdb-server+} manual:
45
+
46
+ - :manual:`Read Preference </core/read-preference/>`
47
+ - :manual:`Read Concern </reference/read-concern/>`
48
+ - :manual:`Write Concern </reference/write-concern/>`
49
+
50
+ .. _kotlin-sync-read-write-config:
51
+
52
+ Configure Read and Write Operations
53
+ -----------------------------------
54
+
55
+ You can control how the driver routes read operations among replica set members
56
+ by setting a read preference. You can also control how the driver waits for
57
+ acknowledgment of read and write operations on a replica set by setting read and
58
+ write concerns.
59
+
60
+ The following sections show how to configure these read and write settings
61
+ at various levels.
62
+
63
+ .. _kotlin-sync-read-write-client:
64
+
65
+ Client Configuration
66
+ ~~~~~~~~~~~~~~~~~~~~
67
+
68
+ This example shows how to set the read preference, read concern, and
69
+ write concern of a ``MongoClient`` instance by passing a ``MongoClientSettings``
70
+ instance to the ``MongoClient.create()`` method. The code configures the
71
+ following settings:
72
+
73
+ - ``secondary`` read preference: Read operations retrieve data from
74
+ secondary replica set members.
75
+ - ``LOCAL`` read concern: Read operations return the instance's most recent data
76
+ without guaranteeing that the data has been written to a majority of the replica
77
+ set members.
78
+ - ``W2`` write concern: The primary replica set member and one secondary member
79
+ must acknowledge the write operation.
80
+
81
+ .. literalinclude:: /includes/configure-crud.kt
82
+ :language: kotlin
83
+ :dedent:
84
+ :start-after: start-client-settings
85
+ :end-before: end-client-settings
86
+
87
+ Alternatively, you can specify the read and write settings in the connection
88
+ URI, which is passed as a parameter to the ``MongoClient.create()`` method:
89
+
90
+ .. literalinclude:: /includes/configure-crud.kt
91
+ :language: kotlin
92
+ :dedent:
93
+ :start-after: start-client-settings-uri
94
+ :end-before: end-client-settings-uri
95
+
96
+ .. _kotlin-sync-read-write-transaction:
97
+
98
+ Transaction Configuration
99
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
100
+
101
+ This example shows how to set the read preference, read concern, and
102
+ write concern of a transaction by passing a ``TransactionOptions``
103
+ instance to the ``withTransaction()`` method. Transactions run within
104
+ **sessions**, which are groupings of related read or write operations that you
105
+ intend to run sequentially. Before applying the transaction options, use the
106
+ ``startSession()`` method to start a session.
107
+
108
+ .. tip::
109
+
110
+ To learn more about sessions, see :manual:`Server Sessions </reference/server-sessions/>`
111
+ in the {+mdb-server+} manual.
112
+
113
+ The example configures the following settings:
114
+
115
+ - ``primary`` read preference: Read operations retrieve data from
116
+ the primary replica set member.
117
+ - ``MAJORITY`` read concern: Read operations return the instance's most recent data
118
+ that has been written to a majority of replica set members.
119
+ - ``W1`` write concern: The primary replica set member must acknowledge the
120
+ write operation.
121
+
122
+ .. literalinclude:: /includes/configure-crud.kt
123
+ :language: kotlin
124
+ :dedent:
125
+ :start-after: start-transaction-settings
126
+ :end-before: end-transaction-settings
127
+
128
+ .. _kotlin-sync-read-write-database:
129
+
130
+ Database Configuration
131
+ ~~~~~~~~~~~~~~~~~~~~~~
132
+
133
+ This example shows how to set the read preference, read concern, and
134
+ write concern of a database called ``test_database`` by chaining setter
135
+ methods to the ``getDatabase()`` method. The code configures the following
136
+ settings:
137
+
138
+ - ``primaryPreferred`` read preference: Read operations retrieve data from
139
+ the primary replica set member, or secondary members if the primary is unavailable.
140
+ - ``AVAILABLE`` read concern: Read operations return the instance's most recent data
141
+ without guaranteeing that the data has been written to a majority of the replica
142
+ set members.
143
+ - ``MAJORITY`` write concern: The majority of all replica set members
144
+ must acknowledge the write operation.
145
+
146
+ .. literalinclude:: /includes/configure-crud.kt
147
+ :language: kotlin
148
+ :dedent:
149
+ :start-after: start-database-settings
150
+ :end-before: end-database-settings
151
+
152
+ .. _kotlin-sync-read-write-collection:
153
+
154
+ Collection Configuration
155
+ ~~~~~~~~~~~~~~~~~~~~~~~~
156
+
157
+ This example shows how to set the read preference, read concern, and
158
+ write concern of a collection called ``test_collection`` by chaining setter
159
+ methods to the ``getCollection()`` method. The code configures the following
160
+ settings:
161
+
162
+ - ``secondaryPreferred`` read preference: Read operations retrieve data from
163
+ secondary replica set members, or the primary members if no secondary members are
164
+ available.
165
+ - ``AVAILABLE`` read concern: Read operations return the instance's most recent data
166
+ without guaranteeing that the data has been written to a majority of the replica
167
+ set members.
168
+ - ``UNACKNOWLEDGED`` write concern: Replica set members do not need to acknowledge
169
+ the write operation.
170
+
171
+ .. literalinclude:: /includes/configure-crud.kt
172
+ :language: kotlin
173
+ :dedent:
174
+ :start-after: start-collection-settings
175
+ :end-before: end-collection-settings
176
+
177
+ .. _kotlin-sync-read-write-advanced:
178
+
179
+ Advanced Read Configurations
180
+ ----------------------------
181
+
182
+ The following sections describe ways to further customize how the {+driver-short+}
183
+ routes read operations.
184
+
185
+ .. _kotlin-sync-sharded-clusters:
186
+
187
+ Sharded Clusters
188
+ ~~~~~~~~~~~~~~~~
189
+
190
+ You can specify a read preference when connecting to a sharded cluster.
191
+ MongoDB uses sharding to divide datasets by key ranges and distribute data across multiple
192
+ database instances. A sharded cluster, or the set of nodes in a sharded deployment,
193
+ includes the following components:
194
+
195
+ - **Shard**: A replica set that contains a subset of the sharded data.
196
+ - **Mongos**: A query router that provides an interface between your
197
+ application and the sharded cluster.
198
+ - **Config servers**: Servers that store the cluster's configuration settings
199
+ and metadata.
200
+
201
+ .. tip::
202
+
203
+ To learn more about sharded clusters, see :manual:`Sharding </sharding/>`
204
+ in the {+mdb-server+} manual.
205
+
206
+ When reading from the replica set shards, ``mongos`` applies your specified read
207
+ preference. The read preference is re-evaluated for each operation.
208
+
209
+ The following example shows how to connect to a sharded cluster and specify a
210
+ ``secondary`` read preference in your connection string:
211
+
212
+ .. literalinclude:: /includes/configure-crud.kt
213
+ :language: kotlin
214
+ :dedent:
215
+ :start-after: start-sharded-cluster-uri
216
+ :end-before: end-sharded-cluster-uri
217
+
218
+ .. _kotlin-sync-tag-sets:
219
+
220
+ Tag Sets
221
+ ~~~~~~~~
222
+
223
+ In {+mdb-server+}, you can apply key-value :manual:`tags
224
+ </core/read-preference-tags/>` to replica set members
225
+ according to any criteria you choose. You can then use those
226
+ tags to target one or more members for a read operation.
227
+
228
+ By default, the {+driver-short+} ignores tags when choosing a member
229
+ to read from. To instruct the {+driver-short+} to prefer certain tags,
230
+ pass the tags as a list to your read preference setter method.
231
+
232
+ Suppose you are connected to a replica set that contains members hosted
233
+ at multiple data centers across the United States. You want the driver to
234
+ prefer reads from secondary replica set members in the following order:
235
+
236
+ 1. Members from the New York data center, tagged with ``("dc", "ny")``
237
+ #. Members from the San Francisco data center, tagged with ``("dc", "sf")``
238
+ #. Any secondary members
239
+
240
+ This code example passes a list of tags representing the preceding replica
241
+ set members to the ``ReadPreference.secondary()`` setter method. Then, the code
242
+ passes the read preference information to the ``withReadPreference()`` method
243
+ to set the read order on the database:
244
+
245
+ .. literalinclude:: /includes/configure-crud.kt
246
+ :language: kotlin
247
+ :dedent:
248
+ :start-after: start-tag-set
249
+ :end-before: end-tag-set
250
+
251
+ Load Balancing
252
+ ~~~~~~~~~~~~~~
253
+
254
+ When connecting to a sharded cluster or a replica set, the {+driver-short+} uses
255
+ **load balancing** to handle read and write requests. Load balancing allows the driver to
256
+ distribute these requests across multiple servers, which avoids overwhelming
257
+ any one server and ensures optimal performance.
258
+
259
+ When connecting to a sharded cluster, the {+driver-short+} determines the closest ``mongos``
260
+ instance by calculating which one has the lowest network round-trip time. Then, the driver
261
+ determines the latency window by adding this ``mongos``'s average round-trip time to the
262
+ :ref:`localThresholdMS value <kotlin-sync-local-threshold>`. The driver load balances requests
263
+ across up to two random ``mongos`` instances that fall within the latency window. For each request,
264
+ the driver chooses the server with the lower operation load by determining its ``operationCount``
265
+ value.
266
+
267
+ When connecting to a replica set, the {+driver-short+} first selects replica set members
268
+ according to your read preference. Then, the driver follows the same process as
269
+ described in the preceding paragraph. After calculating the latency window, the driver
270
+ selects up to two random replica set members that fall within the window and chooses
271
+ the member with the lower ``operationCount`` value to receive the request.
272
+
273
+ .. tip::
274
+
275
+ To learn more about load balancing, see :manual:`Sharded Cluster Balancer
276
+ </core/sharding-balancer-administration/>` in the {+mdb-server+} manual.
277
+
278
+ .. _kotlin-sync-local-threshold:
279
+
280
+ Local Threshold
281
+ ```````````````
282
+
283
+ The {+driver-short+} uses the local threshold value to calculate the
284
+ latency window for server selection. This value determines the servers
285
+ that are eligible to receive read and write requests.
286
+
287
+ By default, the driver uses only ``mongos`` instances or replica set members whose
288
+ ping times are within 15 milliseconds of the nearest server. To
289
+ distribute reads among servers with higher latencies, set the ``localThreshold``
290
+ option in a ``MongoClientSettings`` instance or the ``localThresholdMS`` option
291
+ in your connection URI.
292
+
293
+ .. note::
294
+
295
+ When selecting replica set members from a single ``mongos`` instance, the
296
+ {+driver-short+} ignores the ``localThresholdMS`` option. In this case, use the
297
+ :manual:`localThreshold </reference/program/mongos/#std-option-mongos.--localThreshold>`
298
+ command-line option.
299
+
300
+ The following example connects to a replica set and specifies a local threshold
301
+ of 35 milliseconds. Select the :guilabel:`MongoClientSettings` or :guilabel:`Connection URI`
302
+ tab to see corresponding code for each approach:
303
+
304
+ .. tabs::
305
+
306
+ .. tab:: MongoClientSettings
307
+ :tabid: settings
308
+
309
+ .. literalinclude:: /includes/configure-crud.kt
310
+ :language: rust
311
+ :dedent:
312
+ :start-after: start-local-threshold-settings
313
+ :end-before: end-local-threshold-settings
314
+
315
+
316
+ .. tab:: Connection URI
317
+ :tabid: uri
318
+
319
+ .. literalinclude:: /includes/configure-crud.kt
320
+ :language: rust
321
+ :dedent:
322
+ :start-after: start-local-threshold-uri
323
+ :end-before: end-local-threshold-uri
324
+
325
+ In the preceding example, the {+driver-short+} distributes reads among matching members
326
+ within 35 milliseconds of the closest member's ping time.
327
+
328
+ API Documentation
329
+ -----------------
330
+
331
+ To learn more about any of the methods or types discussed in this
332
+ guide, see the following API documentation:
333
+
334
+ - `MongoClient <{+driver-api+}/-mongo-client/index.html>`__
335
+ - `MongoClientSettings <{+core-api+}/MongoClientSettings.html>`__
336
+ - `TransactionOptions <{+core-api+}/TransactionOptions.html>`_
337
+ - `startTransaction() <{+driver-api+}/-client-session/start-transaction.html>`__
338
+ - `MongoDatabase <{+driver-api+}/-mongo-database/index.html>`__
339
+ - `MongoCollection <{+driver-api+}/-mongo-collection/index.html>`__
340
+ - `TagSet <{+core-api+}/TagSet.html>`_
0 commit comments