From 2dad2a8100698e8e3340f5e784cf5e5634fcb6f0 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 26 Mar 2025 13:01:45 -0400 Subject: [PATCH 1/5] DOCSP-48382: Configure CRUD operations --- source/fundamentals/crud/configure.txt | 368 ++++++++++++++++++++++ source/includes/fundamentals/configure.js | 116 +++++++ 2 files changed, 484 insertions(+) create mode 100644 source/fundamentals/crud/configure.txt create mode 100644 source/includes/fundamentals/configure.js diff --git a/source/fundamentals/crud/configure.txt b/source/fundamentals/crud/configure.txt new file mode 100644 index 000000000..d1f679093 --- /dev/null +++ b/source/fundamentals/crud/configure.txt @@ -0,0 +1,368 @@ +.. _node-configure-crud: + +========================= +Configure CRUD Operations +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: insert, update, replace, delete, options, code example + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to configure read +and write operations. + +Read and Write Settings +----------------------- + +You can control how the driver routes read operations by setting a **read preference**. +You can also control options for how the driver waits for acknowledgment of +read and write operations on a replica set by setting a **read concern** and a +**write concern**. + +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 + +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. + +.. tip:: + + To learn more about the read and write settings, see the following guides in the + {+mdb-server+} manual: + + - :manual:`Read Preference ` + - :manual:`Read Concern ` + - :manual:`Write Concern ` + +This section shows how to configure your read and write settings at each level. + +Client Configuration +~~~~~~~~~~~~~~~~~~~~ + +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-session: + +Session Configuration +~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a session by passing a ``ClientSessionOptions`` object to +the ``startSession()`` 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 +- ``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 +- ``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-session-settings + :end-before: end-session-settings + +.. _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 +~~~~~~~~~~~~~~~~~~~~~~~~ + +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: + +- ``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 <{+api-root+}node/read_preferences.html#node.read_preferences.Primary>`__ +constructor. + +In the following code example, the tag set passed to the ``read_preference`` parameter +instructs {+driver-short+} to prefer reads from the New York data center +(``'dc': 'ny'``) and to fall back to the San Francisco data center (``'dc': 'sf'``): + +.. 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. + +.. _node-configure-collation: + +Collation +--------- + +When you create a collection, you can specify a default **collation** for all operations +you perform on the collection. A collation is a set of language-specific rules for string +comparison, such as for letter case and accent marks. + +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. + +You can specify a collation at the following levels: + +- 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 + + collation: { + locale: , + caseLevel: , + caseFirst: , + strength: , + numericOrdering: , + alternate: , + maxVariable: , + backwards: + } + +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 +` +in the {+mdb-server+} manual. + +.. _node-configure-collation-exs: + +Collation Examples +~~~~~~~~~~~~~~~~~~ + +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. + +This section includes examples that set collations at the collection, +index, and operation levels. + +.. _node-configure-collation-coll-index: + +Set Collection and Index Collations +``````````````````````````````````` + +The following example creates a new collection named ``names`` +and sets its default collation to the ``"fr_CA"`` locale: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-collection-collation + :end-before: end-collection-collation + +You can create an index on the ``names`` collection that specifies a different +collation, as shown in the following example: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-index-collation + :end-before: end-index-collation + +Set an Operation Collation +`````````````````````````` + +You can run an operation on the ``names`` collection, created in +the :ref:`preceding section `, that overrides +the default collation. + +The ``names`` collection contains the following documents: + +.. code-block:: none + + { "_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" } + +The following example calls the ``findOneAndUpdate()`` method to +update the first matching document that has a ``first_name`` value of ``"Gunter"``, +applying a collation with the ``"de@collation=phonebook"`` locale: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-operation-collation + :end-before: end-operation-collation + +In the preceding example, the ``de@collation=phonebook`` locale 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 + + { lastErrorObject: { updatedExisting: true, n: 1 }, + value: { _id: 3, first_name: 'Günter', last_name: 'Krause' }, + ok: 1 } + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `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/includes/fundamentals/configure.js b/source/includes/fundamentals/configure.js new file mode 100644 index 000000000..8c065463c --- /dev/null +++ b/source/includes/fundamentals/configure.js @@ -0,0 +1,116 @@ +const { MongoClient, ReadConcern, ReadPreference, WriteConcern } = require('mongodb'); + +// start-client-settings +const clientOptions = { + readPreference: ReadPreference.SECONDARY, + readConcern: new ReadConcern('local'), + writeConcern: new WriteConcern('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); + + await clientWithUri.connect(); + // end-client-settings-uri + + // start-session-settings + const sessionOptions = { + readPreference: new ReadPreference(ReadPreference.PRIMARY_PREFERRED), + readConcern: new ReadConcern(ReadConcern.LOCAL), + writeConcern: new WriteConcern(WriteConcern.MAJORITY) + }; + + const session = client.startSession(sessionOptions); + // end-session-settings + + // start-transaction-settings + const transactionOptions = { + readPreference: new ReadPreference(ReadPreference.PRIMARY), + readConcern: new ReadConcern(ReadConcern.MAJORITY), + writeConcern: new WriteConcern(1) + }; + + session.startTransaction(transactionOptions); + // end-transaction-settings + + // Sets read and write settings for the "test_database" database + // start-database-settings + const db = client.db('test_database', { + readPreference: new ReadPreference(ReadPreference.PRIMARY_PREFERRED), + readConcern: new ReadConcern(ReadConcern.AVAILABLE), + writeConcern: new WriteConcern(WriteConcern.MAJORITY) + }); + // end-database-settings + + // Sets read and write settings for the "test_collection" collection + // start-collection-settings + const collection = db.collection('test_collection', { + readPreference: new ReadPreference(ReadPreference.SECONDARY_PREFERRED), + readConcern: new ReadConcern(ReadConcern.AVAILABLE), + writeConcern: new WriteConcern(0) + }); + // 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: new 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 From 6aadc31b8b7b55d73b3889d11f931b2c1fb123b7 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 26 Mar 2025 13:10:47 -0400 Subject: [PATCH 2/5] edits, move info --- config/redirects | 2 +- source/crud.txt | 1 - source/crud/configure.txt | 524 ++++++++++++++----------- source/crud/read-write-pref.txt | 244 ------------ source/fundamentals/crud/configure.txt | 368 ----------------- 5 files changed, 287 insertions(+), 852 deletions(-) delete mode 100644 source/crud/read-write-pref.txt delete mode 100644 source/fundamentals/crud/configure.txt 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..e7ad06673 100644 --- a/source/crud/configure.txt +++ b/source/crud/configure.txt @@ -20,302 +20,350 @@ 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 options for how the driver waits for acknowledgment of +read and write operations on a replica set by setting a **read concern** and a +**write concern**. -*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 +- Session +- 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-session: + +Session Configuration +~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a session by passing a ``ClientSessionOptions`` object to +the ``startSession()`` 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 +- ``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 +- ``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-session-settings + :end-before: end-session-settings + +.. _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 -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. +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-collection-settings + :end-before: end-collection-settings -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. +Tag Sets +-------- -.. note:: +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. - 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. +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 <{+api-root+}node/read_preferences.html#node.read_preferences.Primary>`__ +constructor. -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: +In the following code example, the tag set passed to the ``read_preference`` parameter +instructs {+driver-short+} to prefer reads from the New York data center +(``'dc': 'ny'``) and to fall back to the San Francisco data center (``'dc': 'sf'``): -- :manual:`text ` -- :manual:`2d ` -- :manual:`geoHaystack ` +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-tag-set + :end-before: end-tag-set -Collation Parameters -~~~~~~~~~~~~~~~~~~~~ +Local Threshold +--------------- -The collation object contains the following parameters: +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. -.. code-block:: javascript +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. - collation: { - locale: , - caseLevel: , - caseFirst: , - strength: , - numericOrdering: , - alternate: , - maxVariable: , - backwards: - } +The following example specifies a local threshold of 35 milliseconds: -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 -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 -~~~~~~~~~~~~~~~~~~~~~~~~ +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-local-threshold + :end-before: end-local-threshold -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 preceding example, the {+driver-short+} distributes reads between matching members +within 35 milliseconds of the closest member's ping time. -find() and sort() Example -````````````````````````` +.. 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. -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"``. +.. _node-configure-collation: -.. literalinclude:: /code-snippets/collation/find-sort-collation.js - :language: javascript - :start-after: start find sort collation - :end-before: end find sort collation +Collation +--------- -findOneAndUpdate() Example -`````````````````````````` +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. -The following example calls the ``findOneAndUpdate()`` operation on a -collection that uses the default binary collation. The collection contains the -following documents: +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. -.. code-block:: none +You can specify a collation at the following levels: - { "_id" : 1, "first_name" : "Hans" } - { "_id" : 2, "first_name" : "Gunter" } - { "_id" : 3, "first_name" : "Günter" } - { "_id" : 4, "first_name" : "Jürgen" } +- Collection: Sets the default collation for operations on the collection. + You cannot define a collation for an existing collection. -Consider the following ``findOneAndUpdate()`` operation on this collection -which **does not** specify a collation: +- Index: Sets the collation for operations that use the index. -.. 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 +- Operation: Sets the operation's collation and overrides any inherited collations. -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-fields: -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. +Collation Fields +~~~~~~~~~~~~~~~~ -.. literalinclude:: /code-snippets/collation/findOneAndUpdate-collation.js - :language: javascript - :start-after: start findOneAndUpdate collation - :end-before: end findOneAndUpdate collation +The collation object contains the following fields: -Since "Günter" lexically comes before "Gunter" using the -``de@collation=phonebook`` collation specified in ``findOneAndUpdate()``, -the operation returns the following updated document: +.. code-block:: javascript -.. code-block:: none + collation: { + locale: , + caseLevel: , + caseFirst: , + strength: , + numericOrdering: , + alternate: , + maxVariable: , + backwards: + } - { lastErrorObject: { updatedExisting: true, n: 1 }, - value: { _id: 3, first_name: 'Günter' }, - ok: 1 } +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 +` +in the {+mdb-server+} manual. -findOneAndDelete() Example -`````````````````````````` +.. _node-configure-collation-exs: -The following example calls the ``findOneAndDelete()`` operation on a -collection that uses the default binary collation and contains the following -documents: +Collation Examples +~~~~~~~~~~~~~~~~~~ -.. code-block:: none +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. - { "_id" : 1, "a" : "16" } - { "_id" : 2, "a" : "84" } - { "_id" : 3, "a" : "179" } +This section includes examples that set collations at the collection, +index, and operation levels. -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. +.. _node-configure-collation-coll-index: -.. literalinclude:: /code-snippets/collation/findOneAndDelete-collation.js - :language: javascript - :start-after: start findOneAndDelete collation - :end-before: end findOneAndDelete collation +Set Collection and Index Collations +``````````````````````````````````` -After you run the operation above, the collection contains the following -documents: +The following example creates a new collection named ``names`` +and sets its default collation to the ``"fr_CA"`` locale: -.. code-block:: none +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-collection-collation + :end-before: end-collection-collation - { "_id" : 1, "a" : "16" } - { "_id" : 2, "a" : "84" } +You can create an index on the ``names`` collection that specifies a different +collation, as shown in the following example: -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. +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-index-collation + :end-before: end-index-collation -.. literalinclude:: /code-snippets/collation/findOneAndDelete-no-collation.js - :language: javascript - :start-after: start findOneAndDelete no collation - :end-before: end findOneAndDelete no collation +Set an Operation Collation +`````````````````````````` + +You can run an operation on the ``names`` collection, created in +the :ref:`preceding section `, that overrides +the default 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: +The ``names`` collection contains the following documents: .. code-block:: none - { "_id" : 2, "a" : "84" } - { "_id" : 3, "a" : "179" } + { "_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" } -Aggregation Example -``````````````````` +The following example calls the ``findOneAndUpdate()`` method to +update the first matching document that has a ``first_name`` value of ``"Gunter"``, +applying a collation with the ``"de@collation=phonebook"`` locale: -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. +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-operation-collation + :end-before: end-operation-collation -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. +In the preceding example, the ``de@collation=phonebook`` locale 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: -.. note:: +.. code-block:: none - You can specify only one collation on an aggregation. + { lastErrorObject: { updatedExisting: true, n: 1 }, + value: { _id: 3, first_name: 'Günter', last_name: 'Krause' }, + ok: 1 } -.. literalinclude:: /code-snippets/collation/aggregation-collation.js - :language: javascript - :start-after: start aggregation collation - :end-before: end aggregation collation +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `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/fundamentals/crud/configure.txt b/source/fundamentals/crud/configure.txt deleted file mode 100644 index d1f679093..000000000 --- a/source/fundamentals/crud/configure.txt +++ /dev/null @@ -1,368 +0,0 @@ -.. _node-configure-crud: - -========================= -Configure CRUD Operations -========================= - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: insert, update, replace, delete, options, code example - -Overview --------- - -In this guide, you can learn how to use the {+driver-short+} to configure read -and write operations. - -Read and Write Settings ------------------------ - -You can control how the driver routes read operations by setting a **read preference**. -You can also control options for how the driver waits for acknowledgment of -read and write operations on a replica set by setting a **read concern** and a -**write concern**. - -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 - -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. - -.. tip:: - - To learn more about the read and write settings, see the following guides in the - {+mdb-server+} manual: - - - :manual:`Read Preference ` - - :manual:`Read Concern ` - - :manual:`Write Concern ` - -This section shows how to configure your read and write settings at each level. - -Client Configuration -~~~~~~~~~~~~~~~~~~~~ - -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-session: - -Session Configuration -~~~~~~~~~~~~~~~~~~~~~ - -This example shows how to set the read preference, read concern, and -write concern of a session by passing a ``ClientSessionOptions`` object to -the ``startSession()`` 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 -- ``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 -- ``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-session-settings - :end-before: end-session-settings - -.. _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 -~~~~~~~~~~~~~~~~~~~~~~~~ - -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: - -- ``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 <{+api-root+}node/read_preferences.html#node.read_preferences.Primary>`__ -constructor. - -In the following code example, the tag set passed to the ``read_preference`` parameter -instructs {+driver-short+} to prefer reads from the New York data center -(``'dc': 'ny'``) and to fall back to the San Francisco data center (``'dc': 'sf'``): - -.. 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. - -.. _node-configure-collation: - -Collation ---------- - -When you create a collection, you can specify a default **collation** for all operations -you perform on the collection. A collation is a set of language-specific rules for string -comparison, such as for letter case and accent marks. - -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. - -You can specify a collation at the following levels: - -- 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 - - collation: { - locale: , - caseLevel: , - caseFirst: , - strength: , - numericOrdering: , - alternate: , - maxVariable: , - backwards: - } - -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 -` -in the {+mdb-server+} manual. - -.. _node-configure-collation-exs: - -Collation Examples -~~~~~~~~~~~~~~~~~~ - -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. - -This section includes examples that set collations at the collection, -index, and operation levels. - -.. _node-configure-collation-coll-index: - -Set Collection and Index Collations -``````````````````````````````````` - -The following example creates a new collection named ``names`` -and sets its default collation to the ``"fr_CA"`` locale: - -.. literalinclude:: /includes/fundamentals/configure.js - :language: javascript - :dedent: - :start-after: start-collection-collation - :end-before: end-collection-collation - -You can create an index on the ``names`` collection that specifies a different -collation, as shown in the following example: - -.. literalinclude:: /includes/fundamentals/configure.js - :language: javascript - :dedent: - :start-after: start-index-collation - :end-before: end-index-collation - -Set an Operation Collation -`````````````````````````` - -You can run an operation on the ``names`` collection, created in -the :ref:`preceding section `, that overrides -the default collation. - -The ``names`` collection contains the following documents: - -.. code-block:: none - - { "_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" } - -The following example calls the ``findOneAndUpdate()`` method to -update the first matching document that has a ``first_name`` value of ``"Gunter"``, -applying a collation with the ``"de@collation=phonebook"`` locale: - -.. literalinclude:: /includes/fundamentals/configure.js - :language: javascript - :dedent: - :start-after: start-operation-collation - :end-before: end-operation-collation - -In the preceding example, the ``de@collation=phonebook`` locale 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 - - { lastErrorObject: { updatedExisting: true, n: 1 }, - value: { _id: 3, first_name: 'Günter', last_name: 'Krause' }, - ok: 1 } - -API Documentation ------------------ - -To learn more about any of the methods or types discussed in this -guide, see the following API documentation: - -- `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 From e676ca1ebeb42f777fa576bcc7969d5f8ab88450 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 26 Mar 2025 14:29:41 -0400 Subject: [PATCH 3/5] edits --- source/crud/configure.txt | 47 ++++++------------- source/includes/fundamentals/configure.js | 57 +++++++++-------------- 2 files changed, 37 insertions(+), 67 deletions(-) diff --git a/source/crud/configure.txt b/source/crud/configure.txt index e7ad06673..6512403d9 100644 --- a/source/crud/configure.txt +++ b/source/crud/configure.txt @@ -35,7 +35,6 @@ You can set write concern, read concern, and read preference options at the foll levels: - Client, which sets the *default for all operation executions* unless overridden -- Session - Transaction - Database - Collection @@ -85,29 +84,6 @@ URI, which is passed as a parameter to the ``MongoClient`` constructor: :start-after: start-client-settings-uri :end-before: end-client-settings-uri -.. _node-read-write-session: - -Session Configuration -~~~~~~~~~~~~~~~~~~~~~ - -This example shows how to set the read preference, read concern, and -write concern of a session by passing a ``ClientSessionOptions`` object to -the ``startSession()`` 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 -- ``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 -- ``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-session-settings - :end-before: end-session-settings - .. _node-read-write-transaction: Transaction Configuration @@ -119,7 +95,7 @@ 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 +- ``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 @@ -141,10 +117,10 @@ 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 +- ``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 +- ``majority`` write concern: The majority of all replica set members must acknowledge the write operation .. literalinclude:: /includes/fundamentals/configure.js @@ -162,9 +138,9 @@ 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: -- ``SECONDARY_PREFERRED`` read preference: Read operations retrieve data from +- ``secondaryPreferred`` 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 +- ``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 @@ -185,12 +161,16 @@ 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 <{+api-root+}node/read_preferences.html#node.read_preferences.Primary>`__ +pass them as a parameter to your read preference class constructor. -In the following code example, the tag set passed to the ``read_preference`` parameter -instructs {+driver-short+} to prefer reads from the New York data center -(``'dc': 'ny'``) and to fall back to the San Francisco data center (``'dc': 'sf'``): +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: + +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 @@ -347,6 +327,7 @@ a ``first_name`` value of ``"Günter"``, with an umlaut, and returns the following update information: .. code-block:: none + :copyable: false { lastErrorObject: { updatedExisting: true, n: 1 }, value: { _id: 3, first_name: 'Günter', last_name: 'Krause' }, diff --git a/source/includes/fundamentals/configure.js b/source/includes/fundamentals/configure.js index 8c065463c..1a44a3a20 100644 --- a/source/includes/fundamentals/configure.js +++ b/source/includes/fundamentals/configure.js @@ -1,60 +1,49 @@ -const { MongoClient, ReadConcern, ReadPreference, WriteConcern } = require('mongodb'); +const { MongoClient, ReadPreference } = require('mongodb'); // start-client-settings const clientOptions = { readPreference: ReadPreference.SECONDARY, - readConcern: new ReadConcern('local'), - writeConcern: new WriteConcern('2') + readConcern: { level: "local" }, + writeConcern: { w: 2 }, }; -const client = new MongoClient('mongodb://localhost:27017', clientOptions); +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 uri = "mongodb://localhost:27017/?readPreference=secondary&readConcernLevel=local&w=2"; const clientWithUri = new MongoClient(uri); - - await clientWithUri.connect(); // end-client-settings-uri - // start-session-settings - const sessionOptions = { - readPreference: new ReadPreference(ReadPreference.PRIMARY_PREFERRED), - readConcern: new ReadConcern(ReadConcern.LOCAL), - writeConcern: new WriteConcern(WriteConcern.MAJORITY) - }; - - const session = client.startSession(sessionOptions); - // end-session-settings - // start-transaction-settings const transactionOptions = { - readPreference: new ReadPreference(ReadPreference.PRIMARY), - readConcern: new ReadConcern(ReadConcern.MAJORITY), - writeConcern: new WriteConcern(1) + 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 db = client.db('test_database', { - readPreference: new ReadPreference(ReadPreference.PRIMARY_PREFERRED), - readConcern: new ReadConcern(ReadConcern.AVAILABLE), - writeConcern: new WriteConcern(WriteConcern.MAJORITY) + const db = client.db("test_database", { + readPreference: ReadPreference.PRIMARY_PREFERRED, + readConcern: { level: "available" }, + writeConcern: { w: "majority" }, }); // end-database-settings // Sets read and write settings for the "test_collection" collection // start-collection-settings - const collection = db.collection('test_collection', { - readPreference: new ReadPreference(ReadPreference.SECONDARY_PREFERRED), - readConcern: new ReadConcern(ReadConcern.AVAILABLE), - writeConcern: new WriteConcern(0) + const collection = db.collection("test_collection", { + readPreference: ReadPreference.SECONDARY_PREFERRED, + readConcern: { level: "available" }, + writeConcern: { w: 0 }, }); // end-collection-settings @@ -65,14 +54,14 @@ async function main() { const taggedReadPreference = new ReadPreference( ReadPreference.SECONDARY, [ - { dc: 'ny' }, - { dc: 'sf' }, + { dc: "ny" }, + { dc: "sf" }, {} ] ); const dbWithTags = client.db( - 'test_database', + "test_database", { readPreference: taggedReadPreference } ); // end-tag-set @@ -80,9 +69,9 @@ async function main() { // 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: new ReadPreference(ReadPreference.SECONDARY_PREFERRED), + const clientWithLocalThreshold = new MongoClient("mongodb://localhost:27017", { + replicaSet: "repl0", + readPreference: ReadPreference.SECONDARY_PREFERRED, localThresholdMS: 35 }); // end-local-threshold From a153143bc82ba4addc27160f02620e00b3f09733 Mon Sep 17 00:00:00 2001 From: norareidy Date: Thu, 27 Mar 2025 11:10:47 -0400 Subject: [PATCH 4/5] AS feedback --- source/crud/configure.txt | 19 +++++++++++++------ source/includes/fundamentals/configure.js | 12 ++++++++---- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/source/crud/configure.txt b/source/crud/configure.txt index 6512403d9..769328d18 100644 --- a/source/crud/configure.txt +++ b/source/crud/configure.txt @@ -138,7 +138,7 @@ 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: -- ``secondaryPreferred`` read preference: Read operations retrieve data from +- ``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 @@ -207,7 +207,8 @@ within 35 milliseconds of the closest member's ping time. :manual:`localThreshold ` command-line option. -.. _node-configure-collation: +.. _node-fundamentals-collations: +.. _node-collations: Collation --------- @@ -310,9 +311,10 @@ The ``names`` collection contains the following documents: { "_id" : 3, "first_name" : "Günter", "last_name" : "Krause" } { "_id" : 4, "first_name" : "Jürgen", "last_name" : "Weber" } -The following example calls the ``findOneAndUpdate()`` method to -update the first matching document that has a ``first_name`` value of ``"Gunter"``, -applying a collation with the ``"de@collation=phonebook"`` locale: +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:: /includes/fundamentals/configure.js :language: javascript @@ -320,7 +322,7 @@ applying a collation with the ``"de@collation=phonebook"`` locale: :start-after: start-operation-collation :end-before: end-operation-collation -In the preceding example, the ``de@collation=phonebook`` locale instructs +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 @@ -333,6 +335,11 @@ the following update information: value: { _id: 3, first_name: 'Günter', last_name: 'Krause' }, ok: 1 } +.. tip:: + + To learn more about locale variants, see :manual:`Local Variants ` + in the {+mdb-server+} manual. + API Documentation ----------------- diff --git a/source/includes/fundamentals/configure.js b/source/includes/fundamentals/configure.js index 1a44a3a20..d22a23aa0 100644 --- a/source/includes/fundamentals/configure.js +++ b/source/includes/fundamentals/configure.js @@ -31,20 +31,24 @@ async function main() { // Sets read and write settings for the "test_database" database // start-database-settings - const db = client.db("test_database", { + 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 collection = db.collection("test_collection", { + 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 From b8da44ee1905548c682334ac52a97880cd2d89d6 Mon Sep 17 00:00:00 2001 From: norareidy Date: Mon, 31 Mar 2025 13:20:17 -0400 Subject: [PATCH 5/5] tech feedback --- source/crud/configure.txt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/source/crud/configure.txt b/source/crud/configure.txt index 769328d18..92748c8f9 100644 --- a/source/crud/configure.txt +++ b/source/crud/configure.txt @@ -27,9 +27,10 @@ Read and Write Settings ----------------------- You can control how the driver routes read operations by setting a **read preference**. -You can also control options for how the driver waits for acknowledgment of -read and write operations on a replica set by setting a **read concern** and a -**write concern**. +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. You can set write concern, read concern, and read preference options at the following levels: