|
| 1 | +.. _node-crud-write-read-pref: |
| 2 | + |
| 3 | +=============================================== |
| 4 | +Specify How CRUD Operations Run on Replica Sets |
| 5 | +=============================================== |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: reference |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: node.js, 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 | +This list also indicates the increasing order of precedence of the option settings. For |
| 37 | +example, if you set a read concern level for a transaction, it will override a read |
| 38 | +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 write |
| 47 | +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 | +Server manual. For detailed API documentation, see the `WriteConcern API documentation |
| 53 | +<{+api+}/classes/WriteConcern.html>`__. |
| 54 | + |
| 55 | +The following table describes the ``WriteConcern`` 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 | + - `W <{+api+}/types/W.html>`__ |
| 67 | + - Requests acknowledgment that the write operation has propagated to a specified |
| 68 | + number of ``mongod`` instances or to ``mongod`` instances that are labelled specified tags |
| 69 | + |
| 70 | + * - ``wtimeoutMS`` *(optional)* |
| 71 | + - number |
| 72 | + - Specifies a time limit to prevent write operations from blocking indefinitely |
| 73 | + |
| 74 | + * - ``journal`` *(optional)* |
| 75 | + - boolean |
| 76 | + - Requests acknowledgment that the write operation has been written to the on-disk journal |
| 77 | + |
| 78 | +Example: Set the Write Concern for a Single Write Operation |
| 79 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 80 | + |
| 81 | +This code uses custom ``WriteConcern`` settings while creating new a document: |
| 82 | + |
| 83 | +.. code-block:: js |
| 84 | + |
| 85 | + myDB.myCollection.insertOne( |
| 86 | + { name: "anotherDocumentName" }, |
| 87 | + { writeConcern: |
| 88 | + { w: 2, wtimeoutMS: 5000 } |
| 89 | + } |
| 90 | + ); |
| 91 | + |
| 92 | +Example: Retrieve and Apply an Existing Write Concern |
| 93 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 94 | + |
| 95 | +This code uses the ``fromOptions()`` method to construct a ``WriteConcern`` from the |
| 96 | +options of an existing database reference, ``myDB``. Note that ``myDB`` could be replaced |
| 97 | +with a reference to any entity that accepts a write concern option. Then the new write |
| 98 | +concern is applied to a document, ``myDoc``. |
| 99 | + |
| 100 | +.. code-block:: js |
| 101 | + |
| 102 | + const newWriteConcern = WriteConcern.fromOptions(myDB); |
| 103 | + const myDoc = { name: "New Document" }; |
| 104 | + WriteConcern.apply(myDoc,newWriteConcern); |
| 105 | + |
| 106 | +Read Concern |
| 107 | +------------ |
| 108 | + |
| 109 | +The read concern specifies the following behaviors: |
| 110 | + |
| 111 | +- Level of :manual:`causal consistency </core/causal-consistency-read-write-concerns/>` across replica sets |
| 112 | + |
| 113 | +- `Isolation guarantees |
| 114 | + <https://www.mongodb.com/docs/current/core/read-isolation-consistency-recency/>`__ maintained during a query |
| 115 | + |
| 116 | +You can specify the read concern setting by using the ``level`` parameter. The default |
| 117 | +read concern level is ``local``. This means that the client returns the data from the |
| 118 | +replica set member that the client is connected to, with no guarantee that the data has |
| 119 | +been written to all replica set members. Note that lower read concern level requirements |
| 120 | +may reduce latency. |
| 121 | + |
| 122 | +For more information about read concerns or read concern levels, see |
| 123 | +:manual:`Read Concern </reference/read-concern/>` in the Server manual. For more detail on |
| 124 | +the ``ReadConcern`` type and definitions of the read concern levels, see the `ReadConcern <{+api+}/classes/ReadConcern.html>`__ in |
| 125 | +the API documentation. |
| 126 | + |
| 127 | +Example: Set the Read Concern Level of an Aggregation |
| 128 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 129 | + |
| 130 | +This code sets the read concern level of an an aggregation to ``"majority"``: |
| 131 | + |
| 132 | +.. code-block:: js |
| 133 | + |
| 134 | + const pipeline = [ |
| 135 | + {"$match": { |
| 136 | + category: "KITCHENWARE", |
| 137 | + }}, |
| 138 | + {"$unset": [ |
| 139 | + "_id", |
| 140 | + "category", |
| 141 | + ]} |
| 142 | + ]; |
| 143 | + |
| 144 | + result = await myDB.collection("mycollection") |
| 145 | + .aggregate( |
| 146 | + pipeline, |
| 147 | + { readConcern: |
| 148 | + { level: "available" } |
| 149 | + } |
| 150 | + ); |
| 151 | + |
| 152 | +For more information about aggregates, see the :ref:`nodejs-aggregation` page. |
| 153 | + |
| 154 | +Example: Change the Read Concern of a Database |
| 155 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 156 | + |
| 157 | +This code changes the read concern level of a database to ``"local"``: |
| 158 | + |
| 159 | +.. code-block:: js |
| 160 | + |
| 161 | + const options = { readConcern: { level: "local" } }; |
| 162 | + const myDB = client.db("mydb", options); |
| 163 | + |
| 164 | +Read Preference |
| 165 | +--------------- |
| 166 | + |
| 167 | +The read preference determines which member of a replica set MongoDB reads when running a |
| 168 | +query. You can also customize how the server evaluates members. |
| 169 | + |
| 170 | +For more detailed API documentation, see the `ReadPreference API |
| 171 | +documentation <{+api+}/classes/ReadPreference.html>`__. |
| 172 | + |
| 173 | +The following table describes the ``ReadPreference`` parameters: |
| 174 | + |
| 175 | +.. list-table:: |
| 176 | + :widths: 25 25 50 |
| 177 | + :header-rows: 1 |
| 178 | + |
| 179 | + * - Parameter |
| 180 | + - Type |
| 181 | + - Description |
| 182 | + |
| 183 | + * - ``mode`` |
| 184 | + - :manual:`ReadPreferenceMode </core/read-preference/#read-preference-modes-1>` |
| 185 | + - Specifies a requirement or preference for which replica set |
| 186 | + member the server reads from. The default mode, ``primary``, specifies that |
| 187 | + operations read from the primary member of the replica set. |
| 188 | + |
| 189 | + * - ``tags`` *(optional)* |
| 190 | + - :manual:`TagSet List </core/read-preference-tags/#read-preference-tag-set-lists/>` |
| 191 | + - Assigns tags to secondary replica set members to customize how the server evaluates |
| 192 | + them. Tags cannot be used with the ``primary`` read preference mode setting. |
| 193 | + |
| 194 | + * - ``options`` *(optional)* |
| 195 | + - `ReadPreferenceOptions <{+api+}/interfaces/ReadPreferenceOptions.html>`__ |
| 196 | + - Sets various options, including :manual:`hedge </core/read-preference-hedge-option/>` |
| 197 | + and :manual:`maxStalenessSeconds </core/read-preference-staleness/>` that can be |
| 198 | + applied to your read preference. |
| 199 | + |
| 200 | +Example: Set Read Preference and Concerns for a Transaction |
| 201 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 202 | + |
| 203 | +This code sets the read preference, read concern, and write concern for the operations in |
| 204 | +a transaction: |
| 205 | + |
| 206 | +.. code-block:: js |
| 207 | + |
| 208 | + const transactionOptions = { |
| 209 | + readPreference: "primary", |
| 210 | + readConcern: { level: "local" }, |
| 211 | + writeConcern: { w: "majority" }, |
| 212 | + }; |
| 213 | + |
| 214 | + const session = client.startSession(); |
| 215 | + session.startTransaction(transactionOptions); |
| 216 | + // ... |
| 217 | + await session.commitTransaction(); |
| 218 | + await session.endSession(); |
| 219 | + |
| 220 | +For more information about transactions, see :ref:`nodejs-transactions`. |
| 221 | + |
| 222 | +Example: Set the Read Preference of a Cluster in the Connection String |
| 223 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 224 | + |
| 225 | +This code example creates a MongoClient that uses the "secondary" read preference mode |
| 226 | +when performing queries on a cluster: |
| 227 | + |
| 228 | +.. code-block:: js |
| 229 | + |
| 230 | + const uri = "mongodb+srv://<user>:<password>@<cluster-url>?readPreference=secondary&maxStalenessSeconds=120"; |
| 231 | + const client = new MongoClient(uri); |
| 232 | + |
| 233 | +This example also sets the ``maxStalenessSeconds`` option. For more information about connection string options, see the :manual:`Connection String Options </reference/connection-string/#connection-string-options>` |
| 234 | +section in the manual. |
| 235 | + |
| 236 | +API Documentation |
| 237 | +----------------- |
| 238 | + |
| 239 | +To learn more about the methods and types mentioned in this guide, see the following API |
| 240 | +documentation: |
| 241 | + |
| 242 | +- `API WriteConcern <{+api+}/classes/WriteConcern.html>`__ |
| 243 | +- `API ReadConcern <{+api+}/classes/ReadConcern.html>`__ |
| 244 | +- `API ReadPreference <{+api+}/classes/ReadPreference.html>`__ |
0 commit comments