diff --git a/config/redirects b/config/redirects index a02dfd519..cb6c2f2ad 100644 --- a/config/redirects +++ b/config/redirects @@ -43,7 +43,7 @@ raw: ${prefix}/stable -> ${base}/current/ [*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/ -> ${base}/${version}/crud/query/ [*-master]: ${prefix}/${version}/fundamentals/crud/query-document/ -> ${base}/${version}/crud/query/query-document/ [*-master]: ${prefix}/${version}/fundamentals/crud/compound-operations/ -> ${base}/${version}/crud/compound-operations/ -[*-master]: ${prefix}/${version}/fundamentals/crud/read-write-pref/ -> ${base}/${version}/crud/read-write-pref/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-write-pref/ -> ${base}/${version}/crud/configure/ [*-master]: ${prefix}/${version}/fundamentals/transactions/ -> ${base}/${version}/crud/transactions/ [*-master]: ${prefix}/${version}/fundamentals/gridfs/ -> ${base}/${version}/crud/gridfs/ [*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/retrieve/ -> ${base}/${version}/crud/query/retrieve/ diff --git a/source/crud.txt b/source/crud.txt index abf96d299..6a2ea2af3 100644 --- a/source/crud.txt +++ b/source/crud.txt @@ -31,7 +31,6 @@ CRUD Operations Compound Operations Transactions Configure CRUD Operations - Operations on Replica Sets Store Large Files CRUD (Create, Read, Update, Delete) operations enable you to work with diff --git a/source/crud/configure.txt b/source/crud/configure.txt index 521f75e68..92748c8f9 100644 --- a/source/crud/configure.txt +++ b/source/crud/configure.txt @@ -20,81 +20,226 @@ Configure CRUD Operations Overview -------- -In this guide, you can learn how to configure read and write operations in {+driver-short+}. +In this guide, you can learn how to use the {+driver-short+} to configure read +and write operations. -.. _node-fundamentals-collations: -.. _node-collations: +Read and Write Settings +----------------------- -Collations ----------- +You can control how the driver routes read operations by setting a **read preference**. +You can also control how the driver handles data consistency and durability by setting +a **read concern** or **write concern**. Read concerns specify the level of durability +required for the data when performing read operations, and write concerns specify +how the driver waits for acknowledgment of write operations on a replica set. -*Collations are available in MongoDB 3.4 and later.* +You can set write concern, read concern, and read preference options at the following +levels: -You can use **collations**, a set of sorting rules, to run operations using -string ordering for specific languages and locales (a community or region that -shares common language idioms). +- Client, which sets the *default for all operation executions* unless overridden +- Transaction +- Database +- Collection -MongoDB sorts strings using *binary collation* by default. This collation -method uses the `ASCII standard `_ -character values to compare and order strings. Languages and locales -have specific character ordering conventions that differ from the ASCII -standard. +The preceding list also indicates the increasing order of precedence of the option settings. For +example, if you set a read concern level for a transaction, it will override a read +concern level set for the client. -For example, in Canadian French, the right-most accented character determines -the ordering for strings when the other characters are the same. Consider the -following French words: **cote**, **coté**, **côte**, and **côté**. +.. tip:: -MongoDB sorts them in the following order using the default binary collation: + To learn more about the read and write settings, see the following guides in the + {+mdb-server+} manual: -.. code-block:: none + - :manual:`Read Preference ` + - :manual:`Read Concern ` + - :manual:`Write Concern ` - cote - coté - côte - côté +This section shows how to configure your read and write settings at each level. -MongoDB sorts them in the following order using the Canadian French collation: +Client Configuration +~~~~~~~~~~~~~~~~~~~~ -.. code-block:: none +This example shows how to set the read preference, read concern, and +write concern of a ``MongoClient`` instance by passing a ``MongoClientOptions`` +object to the constructor. The code configures the following settings: + +- ``SECONDARY`` read preference: Read operations retrieve data from + secondary replica set members +- ``local`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``2`` write concern: The primary and one secondary replica set member + must acknowledge the write operation + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-client-settings + :end-before: end-client-settings + +Alternatively, you can specify the read and write settings in the connection +URI, which is passed as a parameter to the ``MongoClient`` constructor: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-client-settings-uri + :end-before: end-client-settings-uri + +.. _node-read-write-transaction: + +Transaction Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a transaction by passing a ``TransactionOptions`` object +to the ``startTransaction()`` method. The code configures the following settings: + +- ``PRIMARY`` read preference: Read operations retrieve data from + the primary replica set member +- ``majority`` read concern: Read operations return the instance's most recent data + that has been written to a majority of replica set members +- ``1`` write concern: The primary replica set member must acknowledge the + write operation + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-transaction-settings + :end-before: end-transaction-settings + +.. _node-read-write-database: + +Database Configuration +~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a database called ``test_database`` by passing a ``DbOptions`` +object to the ``db()`` method. The code configures the following settings: + +- ``PRIMARY_PREFERRED`` read preference: Read operations retrieve data from + the primary replica set member, or secondary members if the primary is unavailable +- ``available`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``majority`` write concern: The majority of all replica set members + must acknowledge the write operation + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-database-settings + :end-before: end-database-settings + +.. _node-read-write-collection: + +Collection Configuration +~~~~~~~~~~~~~~~~~~~~~~~~ - cote - côte - coté - côté +This example shows how to set the read preference, read concern, and +write concern of a collection called ``test_collection`` by passing a ``CollectionOptions`` +object to the ``collection()`` method. The code configures the following settings: -Using Collations -~~~~~~~~~~~~~~~~~~ +- ``SECONDARY_PREFERRED`` read preference: Read operations retrieve data from + secondary replica set members, or the primary members if no secondaries are available +- ``available`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``0`` write concern: Does not request acknowledgment of the write operation + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-collection-settings + :end-before: end-collection-settings + +Tag Sets +-------- + +In {+mdb-server+}, you can apply key-value :manual:`tags +` to replica-set +members according to any criteria you choose. You can then use +those tags to target one or more members for a read operation. + +By default, the {+driver-short+} ignores tags when choosing a member +to read from. To instruct the {+driver-short+} to prefer certain tags, +pass them as a parameter to your read preference class +constructor. -You can specify a collation when you create a new collection or new index. You -can also specify a collation for :doc:`CRUD operations ` -and aggregations. +This code example sets the ``readPreference`` option to a tag set that +instructs ``test_database`` to prefer reads from secondary replica set +members in the following order: -When you create a new collection with a collation, you define the default -collation for any of the :manual:`operations that support collation -` called on that -collection. You can override the collation for an operation by specifying a -different one. +1. Members from the New York data center (``{ dc: 'ny' }``) +#. Members from the San Francisco data center (``{ dc: 'sf' }``) +#. Any secondary members (``{}``) + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-tag-set + :end-before: end-tag-set + +Local Threshold +--------------- + +If multiple replica-set members match the read preference and tag sets you specify, +the {+driver-short+} reads from the nearest replica set members, chosen according to +their ping time. + +By default, the driver uses only those members whose ping times are within 15 milliseconds +of the nearest member for queries. To distribute reads between members with +higher latencies, pass the ``localThresholdMS`` option to the ``MongoClient()`` constructor. + +The following example specifies a local threshold of 35 milliseconds: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-local-threshold + :end-before: end-local-threshold + +In the preceding example, the {+driver-short+} distributes reads between matching members +within 35 milliseconds of the closest member's ping time. .. note:: + + The {+driver-short+} ignores the value of ``localThresholdMS`` when communicating with a + replica set through a ``mongos`` instance. In this case, use the + :manual:`localThreshold ` + command-line option. - Currently, you cannot create a collation on an existing collection. To use - collations with an existing collection, create an index with the collation - and specify the same collation in your operations on it. +.. _node-fundamentals-collations: +.. _node-collations: -When you create an index with a collation, you specify the sort order for -operations that use that index. To use the collation in the index, you -must provide a matching collation in the operation, and the operation must -use the index. While most index types support collation, the following -types support only binary comparison: +Collation +--------- -- :manual:`text ` -- :manual:`2d ` -- :manual:`geoHaystack ` +You can specify a **collation** to modify the behavior of read +and write operations. A collation is a set of language-specific rules for string +comparison, such as for letter case and accent marks. -Collation Parameters -~~~~~~~~~~~~~~~~~~~~ +MongoDB sorts strings using *binary collation* by default. This default +collation uses the `ASCII standard `_ +character values to compare and order strings. Languages and locales +have specific character ordering conventions that differ from the ASCII +standard, and you can choose to apply a different set of collation rules +to your operation. + +You can specify a collation at the following levels: -The collation object contains the following parameters: +- Collection: Sets the default collation for operations on the collection. + You cannot define a collation for an existing collection. + +- Index: Sets the collation for operations that use the index. + +- Operation: Sets the operation's collation and overrides any inherited collations. + +.. _node-configure-collation-fields: + +Collation Fields +~~~~~~~~~~~~~~~~ + +The collation object contains the following fields: .. code-block:: javascript @@ -109,213 +254,105 @@ The collation object contains the following parameters: backwards: } -You must specify the ``locale`` field in the collation; all other fields -are optional. For a complete list of supported locales and the default values +When setting the ``collation`` option, you must specify the ``locale`` field. +All other fields are optional. For a complete list of supported locales and the default values for the ``locale`` fields, see :manual:`Supported Languages and Locales -`. -For descriptions of each field, see the :manual:`Collation Document MongoDB -manual entry `. - -Set a Default Collation on a Collection -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In the following example, we create a new collection called ``souvenirs`` and -assign a default collation with the ``"fr_CA"`` locale. The collation applies -to all :manual:`operations that support collation -` performed on that -collection. - -.. literalinclude:: /code-snippets/collation/collection-collation.js - :language: javascript - :start-after: start collection collation - :end-before: end collection collation - -Any of the operations that support collations automatically apply the collation -defined on the collection. The query below searches the ``souvenirs`` -collection and applies the ``"fr_CA"`` locale collation: - -.. literalinclude:: /code-snippets/collation/collection-auto-collation.js - :language: javascript - :start-after: start auto collation - :end-before: end auto collation - -You can specify a different collation as a parameter in an operation that -supports collations. The following query specifies the ``"is"`` Iceland locale -and ``caseFirst`` optional parameter with the value ``"upper"``: - -.. literalinclude:: /code-snippets/collation/collection-specify-collation.js - :language: javascript - :start-after: start specified collation - :end-before: end specified collation - -Assign a Collation to an Index -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In the following example, we create a new index on the ``title`` field of -a collection with a collation set to the ``"en_US"`` locale. - -.. literalinclude:: /code-snippets/collation/index-collation.js - :language: javascript - :start-after: start create index collation - :end-before: end create index collation - -The following query uses the index we created: - -.. literalinclude:: /code-snippets/collation/query-index-collation.js - :language: javascript - :start-after: start query index collation - :end-before: end query index collation - -The following queries **do not** use the index that we created. The first -query does not include a collation and the second contains a different -strength value than the collation on the index. - -.. literalinclude:: /code-snippets/collation/query-not-indexed-collation.js - :language: javascript - :start-after: start not indexed collation - :end-before: end not indexed collation - -.. literalinclude:: /code-snippets/collation/query-index-no-collation.js - :language: javascript - :start-after: start index no collation - :end-before: end index no collation - -Collation Query Examples -~~~~~~~~~~~~~~~~~~~~~~~~ - -Operations that read, update, and delete documents from a collection can use -collations. This section includes examples of a selection of these. See the -MongoDB manual for a full list of :manual:`operations that support collation -`. +` +in the {+mdb-server+} manual. -find() and sort() Example -````````````````````````` - -The following example calls both ``find()`` and ``sort()`` on a collection -that uses the default binary collation. We use the German collation by -setting the value of the ``locale`` parameter to ``"de"``. - -.. literalinclude:: /code-snippets/collation/find-sort-collation.js - :language: javascript - :start-after: start find sort collation - :end-before: end find sort collation - -findOneAndUpdate() Example -`````````````````````````` - -The following example calls the ``findOneAndUpdate()`` operation on a -collection that uses the default binary collation. The collection contains the -following documents: - -.. code-block:: none +.. _node-configure-collation-exs: - { "_id" : 1, "first_name" : "Hans" } - { "_id" : 2, "first_name" : "Gunter" } - { "_id" : 3, "first_name" : "Günter" } - { "_id" : 4, "first_name" : "Jürgen" } +Collation Examples +~~~~~~~~~~~~~~~~~~ -Consider the following ``findOneAndUpdate()`` operation on this collection -which **does not** specify a collation: +To specify a collation, create a ``collation`` object and set its +``locale`` field to the language collation you want to use. Then, +pass this object as an options parameter to the method corresponding +to the target collation level. -.. literalinclude:: /code-snippets/collation/findOneAndUpdate-default-order-collation.js - :language: javascript - :start-after: start findOneAndUpdate default order collation - :end-before: end findOneAndUpdate default order collation +This section includes examples that set collations at the collection, +index, and operation levels. -Since "Gunter" is the first sorted result when using a binary collation, none -of the documents come lexically before and match the ``$lt`` comparison -operator in the query document. As a result, the operation does not update any -documents. +.. _node-configure-collation-coll-index: -Consider the same operation with a collation specified with the locale set to -``de@collation=phonebook``. This locale specifies the ``collation=phonebook`` -option which contains rules for prioritizing proper nouns, identified by -capitalization of the first letter. The ``de@collation=phonebook`` locale and -option sorts characters with umlauts before the same characters without -umlauts. +Set Collection and Index Collations +``````````````````````````````````` -.. literalinclude:: /code-snippets/collation/findOneAndUpdate-collation.js - :language: javascript - :start-after: start findOneAndUpdate collation - :end-before: end findOneAndUpdate collation +The following example creates a new collection named ``names`` +and sets its default collation to the ``"fr_CA"`` locale: -Since "Günter" lexically comes before "Gunter" using the -``de@collation=phonebook`` collation specified in ``findOneAndUpdate()``, -the operation returns the following updated document: +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-collection-collation + :end-before: end-collection-collation -.. code-block:: none +You can create an index on the ``names`` collection that specifies a different +collation, as shown in the following example: - { lastErrorObject: { updatedExisting: true, n: 1 }, - value: { _id: 3, first_name: 'Günter' }, - ok: 1 } +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-index-collation + :end-before: end-index-collation -findOneAndDelete() Example +Set an Operation Collation `````````````````````````` -The following example calls the ``findOneAndDelete()`` operation on a -collection that uses the default binary collation and contains the following -documents: - -.. code-block:: none - - { "_id" : 1, "a" : "16" } - { "_id" : 2, "a" : "84" } - { "_id" : 3, "a" : "179" } +You can run an operation on the ``names`` collection, created in +the :ref:`preceding section `, that overrides +the default collation. -In this example, we set the ``numericOrdering`` collation parameter to ``true`` -to sort numeric strings based on their numerical order instead of their -lexical order. - -.. literalinclude:: /code-snippets/collation/findOneAndDelete-collation.js - :language: javascript - :start-after: start findOneAndDelete collation - :end-before: end findOneAndDelete collation - -After you run the operation above, the collection contains the following -documents: +The ``names`` collection contains the following documents: .. code-block:: none - { "_id" : 1, "a" : "16" } - { "_id" : 2, "a" : "84" } + { "_id" : 1, "first_name" : "Hans", "last_name" : "Muller" } + { "_id" : 2, "first_name" : "Gunter", "last_name" : "Braun" } + { "_id" : 3, "first_name" : "Günter", "last_name" : "Krause" } + { "_id" : 4, "first_name" : "Jürgen", "last_name" : "Weber" } -If you perform the same operation without collation on the original -collection of three documents, it matches documents based on the lexical value -of the strings (``"16"``, ``"84"``, and ``"179"``), and deletes the first -document it finds that matches the query criteria. +This example calls the ``findOneAndUpdate()`` method to update +the first matching document that has a ``first_name`` value of ``"Gunter"``. +The code applies a collation with the ``"de"`` locale and the ``"phonebook"`` +locale variant: -.. literalinclude:: /code-snippets/collation/findOneAndDelete-no-collation.js - :language: javascript - :start-after: start findOneAndDelete no collation - :end-before: end findOneAndDelete no collation +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-operation-collation + :end-before: end-operation-collation -Since all the documents contain lexical values in the ``a`` field that -match the criteria (greater than the lexical value of ``"100"``), the operation -removes the first result. After you run the operation above, the collection -contains the following documents: +In the preceding example, the ``phonebook`` locale variant instructs +the driver to sort characters with umlauts before the same characters without +umlauts. As a result, the operation matches the document that has +a ``first_name`` value of ``"Günter"``, with an umlaut, and returns +the following update information: .. code-block:: none + :copyable: false - { "_id" : 2, "a" : "84" } - { "_id" : 3, "a" : "179" } - -Aggregation Example -``````````````````` + { lastErrorObject: { updatedExisting: true, n: 1 }, + value: { _id: 3, first_name: 'Günter', last_name: 'Krause' }, + ok: 1 } -To use collation with the `aggregate <{+api+}/classes/Collection.html#aggregate>`__ -operation, pass the collation document in the options field, after the -array of pipeline stages. +.. tip:: -The following example shows an aggregation pipeline on a collection that uses -the default binary collation. The aggregation groups the ``first_name`` field, -counts the total number of results in each group, and sorts the results by -the German phonebook (``"de@collation=phonebook"`` locale) order. + To learn more about locale variants, see :manual:`Local Variants ` + in the {+mdb-server+} manual. -.. note:: +API Documentation +----------------- - You can specify only one collation on an aggregation. +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: -.. literalinclude:: /code-snippets/collation/aggregation-collation.js - :language: javascript - :start-after: start aggregation collation - :end-before: end aggregation collation +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ +- `ClientSessionOptions <{+api+}/interfaces/ClientSessionOptions.html>`__ +- `TransactionOptions <{+api+}/interfaces/TransactionOptions.html>`__ +- `DbOptions <{+api+}/interfaces/DbOptions.html>`__ +- `CollectionOptions <{+api+}/interfaces/CollectionOptions.html>`__ +- `collation <{+api+}/interfaces/CreateCollectionOptions.html#collation>`__ \ No newline at end of file diff --git a/source/crud/read-write-pref.txt b/source/crud/read-write-pref.txt deleted file mode 100644 index 376f64530..000000000 --- a/source/crud/read-write-pref.txt +++ /dev/null @@ -1,244 +0,0 @@ -.. _node-crud-write-read-pref: - -=============================================== -Specify How CRUD Operations Run on Replica Sets -=============================================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: node.js, customize, preferences, replica set, consistency - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -In this guide, you can learn how to use the **write concern**, **read concern**, and -**read preference** configurations to modify the way that MongoDB runs -create, read, update, and delete (CRUD) operations on replica sets. - -You can set write concern, read concern, and read preference options at the following -levels: - -- Client, which sets the *default for all operation executions* unless overridden -- Session -- Transaction -- Database -- Collection - -This list also indicates the increasing order of precedence of the option settings. For -example, if you set a read concern level for a transaction, it will override a read -concern level set for the client. - -These options allow you to customize the causal consistency and availability of the data -in your replica sets. - -Write Concern -------------- - -The write concern specifies the level of acknowledgement requested from MongoDB for write -operations, such as an insert or update, before the operation successfully returns. -Operations that do not specify an explicit write concern inherit the global default write -concern settings. - -For more information, see :manual:`Write Concern ` in the -Server manual. For detailed API documentation, see the `WriteConcern API documentation -<{+api+}/classes/WriteConcern.html>`__. - -The following table describes the ``WriteConcern`` parameters: - -.. list-table:: - :header-rows: 1 - :widths: 25 25 50 - - * - Parameter - - Type - - Description - - * - ``w`` *(optional)* - - `W <{+api+}/types/W.html>`__ - - Requests acknowledgment that the write operation has propagated to a specified - number of ``mongod`` instances or to ``mongod`` instances that are labelled specified tags - - * - ``wtimeoutMS`` *(optional)* - - number - - Specifies a time limit to prevent write operations from blocking indefinitely - - * - ``journal`` *(optional)* - - boolean - - Requests acknowledgment that the write operation has been written to the on-disk journal - -Example: Set the Write Concern for a Single Write Operation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code uses custom ``WriteConcern`` settings while creating new a document: - -.. code-block:: js - - myDB.myCollection.insertOne( - { name: "anotherDocumentName" }, - { writeConcern: - { w: 2, wtimeoutMS: 5000 } - } - ); - -Example: Retrieve and Apply an Existing Write Concern -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code uses the ``fromOptions()`` method to construct a ``WriteConcern`` from the -options of an existing database reference, ``myDB``. Note that ``myDB`` could be replaced -with a reference to any entity that accepts a write concern option. Then the new write -concern is applied to a document, ``myDoc``. - -.. code-block:: js - - const newWriteConcern = WriteConcern.fromOptions(myDB); - const myDoc = { name: "New Document" }; - WriteConcern.apply(myDoc,newWriteConcern); - -Read Concern ------------- - -The read concern specifies the following behaviors: - -- Level of :manual:`causal consistency ` across replica sets - -- `Isolation guarantees - `__ maintained during a query - -You can specify the read concern setting by using the ``level`` parameter. The default -read concern level is ``local``. This means that the client returns the data from the -replica set member that the client is connected to, with no guarantee that the data has -been written to all replica set members. Note that lower read concern level requirements -may reduce latency. - -For more information about read concerns or read concern levels, see -:manual:`Read Concern ` in the Server manual. For more detail on -the ``ReadConcern`` type and definitions of the read concern levels, see the `ReadConcern <{+api+}/classes/ReadConcern.html>`__ in -the API documentation. - -Example: Set the Read Concern Level of an Aggregation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code sets the read concern level of an an aggregation to ``"majority"``: - -.. code-block:: js - - const pipeline = [ - {"$match": { - category: "KITCHENWARE", - }}, - {"$unset": [ - "_id", - "category", - ]} - ]; - - result = await myDB.collection("mycollection") - .aggregate( - pipeline, - { readConcern: - { level: "available" } - } - ); - -For more information about aggregates, see the :ref:`nodejs-aggregation` page. - -Example: Change the Read Concern of a Database -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code changes the read concern level of a database to ``"local"``: - -.. code-block:: js - - const options = { readConcern: { level: "local" } }; - const myDB = client.db("mydb", options); - -Read Preference ---------------- - -The read preference determines which member of a replica set MongoDB reads when running a -query. You can also customize how the server evaluates members. - -For more detailed API documentation, see the `ReadPreference API -documentation <{+api+}/classes/ReadPreference.html>`__. - -The following table describes the ``ReadPreference`` parameters: - -.. list-table:: - :widths: 25 25 50 - :header-rows: 1 - - * - Parameter - - Type - - Description - - * - ``mode`` - - :manual:`ReadPreferenceMode ` - - Specifies a requirement or preference for which replica set - member the server reads from. The default mode, ``primary``, specifies that - operations read from the primary member of the replica set. - - * - ``tags`` *(optional)* - - :manual:`TagSet List ` - - Assigns tags to secondary replica set members to customize how the server evaluates - them. Tags cannot be used with the ``primary`` read preference mode setting. - - * - ``options`` *(optional)* - - `ReadPreferenceOptions <{+api+}/interfaces/ReadPreferenceOptions.html>`__ - - Sets various options, including :manual:`hedge ` - and :manual:`maxStalenessSeconds ` that can be - applied to your read preference. - -Example: Set Read Preference and Concerns for a Transaction -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code sets the read preference, read concern, and write concern for the operations in -a transaction: - -.. code-block:: js - - const transactionOptions = { - readPreference: "primary", - readConcern: { level: "local" }, - writeConcern: { w: "majority" }, - }; - - const session = client.startSession(); - session.startTransaction(transactionOptions); - // ... - await session.commitTransaction(); - await session.endSession(); - -For more information about transactions, see :ref:`nodejs-transactions`. - -Example: Set the Read Preference of a Cluster in the Connection String -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code example creates a MongoClient that uses the "secondary" read preference mode -when performing queries on a cluster: - -.. code-block:: js - - const uri = "mongodb+srv://:@?readPreference=secondary&maxStalenessSeconds=120"; - const client = new MongoClient(uri); - -This example also sets the ``maxStalenessSeconds`` option. For more information about connection string options, see the :manual:`Connection String Options ` -section in the manual. - -API Documentation ------------------ - -To learn more about the methods and types mentioned in this guide, see the following API -documentation: - -- `API WriteConcern <{+api+}/classes/WriteConcern.html>`__ -- `API ReadConcern <{+api+}/classes/ReadConcern.html>`__ -- `API ReadPreference <{+api+}/classes/ReadPreference.html>`__ \ No newline at end of file diff --git a/source/includes/fundamentals/configure.js b/source/includes/fundamentals/configure.js new file mode 100644 index 000000000..d22a23aa0 --- /dev/null +++ b/source/includes/fundamentals/configure.js @@ -0,0 +1,109 @@ +const { MongoClient, ReadPreference } = require('mongodb'); + +// start-client-settings +const clientOptions = { + readPreference: ReadPreference.SECONDARY, + readConcern: { level: "local" }, + writeConcern: { w: 2 }, +}; + +const client = new MongoClient("mongodb://localhost:27017", clientOptions); +// end-client-settings + +async function main() { + await client.connect(); + + // start-client-settings-uri + const uri = "mongodb://localhost:27017/?readPreference=secondary&readConcernLevel=local&w=2"; + const clientWithUri = new MongoClient(uri); + // end-client-settings-uri + + // start-transaction-settings + const transactionOptions = { + readPreference: ReadPreference.PRIMARY, + readConcern: { level: "majority" }, + writeConcern: { w: 1 }, + }; + + const session = client.startSession(); + session.startTransaction(transactionOptions); + // end-transaction-settings + + // Sets read and write settings for the "test_database" database + // start-database-settings + const dbOptions = { + readPreference: ReadPreference.PRIMARY_PREFERRED, + readConcern: { level: "available" }, + writeConcern: { w: "majority" }, + }; + + const db = client.db("test_database", dbOptions); + // end-database-settings + + // Sets read and write settings for the "test_collection" collection + // start-collection-settings + const collOptions = { + readPreference: ReadPreference.SECONDARY_PREFERRED, + readConcern: { level: "available" }, + writeConcern: { w: 0 }, + }; + + const collection = db.collection("test_collection", collOptions); + // end-collection-settings + + // Instructs the library to prefer reads from secondary replica set members + // located in New York, followed by a secondary in San Francisco, and + // lastly fall back to any secondary. + // start-tag-set + const taggedReadPreference = new ReadPreference( + ReadPreference.SECONDARY, + [ + { dc: "ny" }, + { dc: "sf" }, + {} + ] + ); + + const dbWithTags = client.db( + "test_database", + { readPreference: taggedReadPreference } + ); + // end-tag-set + + // Instructs the library to distribute reads between members within 35 milliseconds + // of the closest member's ping time + // start-local-threshold + const clientWithLocalThreshold = new MongoClient("mongodb://localhost:27017", { + replicaSet: "repl0", + readPreference: ReadPreference.SECONDARY_PREFERRED, + localThresholdMS: 35 + }); + // end-local-threshold + + // Create the "souvenirs" collection and specify the French Canadian collation + // start-collection-collation + const db = client.db("db") + db.createCollection("names", { + collation: { locale: "fr_CA" }, + }); + // end-collection-collation + + // Create an index collation on the "souvenirs" collection + // start-index-collation + const coll = db.collection("names"); + coll.createIndex( + { "last_name" : 1 }, + { "collation" : { "locale" : "en_US" } }); + // end-index-collation + + // Apply a collation to an operation + // start-operation-collation + coll.findOneAndUpdate( + { first_name: { $lt: "Gunter" } }, + { $set: { verified: true } }, + { collation: { locale: "de@collation=phonebook" } }, + ); + // end-operation-collation +} + +main().catch(console.error); \ No newline at end of file