diff --git a/source/databases-collections.txt b/source/databases-collections.txt index 1a650dc9..456e65f1 100644 --- a/source/databases-collections.txt +++ b/source/databases-collections.txt @@ -187,10 +187,8 @@ The following example deletes the ``test_collection`` collection: Configure Read and Write Operations ----------------------------------- -You can control how the library routes read operations by setting a **read preference**. -You can also control options for how the library waits for acknowledgment of -read and write operations on a replica set by setting a **read concern** and a -**write concern**. +You can control how read and write operations run on replica sets +by specifying a read preference, read concern, or write concern. By default, databases inherit read and write settings from the ``MongoDB\Client`` instance. Collections inherit these settings from the ``MongoDB\Client`` or @@ -199,114 +197,8 @@ You can change these settings by passing an options array to the ``MongoDB\Client::selectDatabase()``, ``MongoDB\Client::selectCollection()``, or ``MongoDB\Database::selectCollection()`` methods. -To change the read preference, read concern, and write concern of your database -or collection, set the following options in the array parameter: - -- ``readPreference``: Sets the read preference. For a list of available read - preferences, see :php:`MongoDB\Driver\ReadPreference ` - in the extension API documentation. -- ``readConcern``: Sets the read concern. For a list of available read - concerns, see :php:`MongoDB\Driver\ReadConcern ` - in the extension API documentation. -- ``writeConcern``: Sets the write concern. For a list of available write - concerns, see :php:`MongoDB\Driver\WriteConcern ` - in the extension API documentation. - -.. tip:: - - To learn more about read preferences and read and write concerns, see the - following guides in the MongoDB Server manual: - - - :manual:`Read Preference ` - - :manual:`Read Concern ` - - :manual:`Write Concern ` - -Database Configuration Example -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example shows how to set the read preference, read concern, and -write concern of a database called ``test_database`` by passing an options -array to ``selectDatabase()``: - -.. literalinclude:: /includes/databases-collections/databases-collections.php - :language: php - :dedent: - :start-after: start-database-settings - :end-before: end-database-settings - -Collection Configuration Example -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example shows how to set the read preference, read concern, and -write concern of a collection called ``test_collection`` by passing an options -array to ``selectCollection()``: - -.. literalinclude:: /includes/databases-collections/databases-collections.php - :language: php - :dedent: - :start-after: start-collection-settings - :end-before: end-collection-settings - -Advanced Read Configurations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -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 {+php-library+} ignores tags when choosing a member -to read from. To instruct the {+php-library+} to prefer certain tags, -pass them as a parameter to your ``MongoDB\Driver\ReadPreference`` class -constructor. Then, set the ``MongoDB\Driver\ReadPreference`` object as -the value of the ``readPreference`` database option. - -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/databases-collections/databases-collections.php - :language: php - :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 {+php-library+} reads from the nearest replica-set members, chosen according to -their ping time. - -By default, the library uses only members whose ping times are within 15 milliseconds -of the nearest member for queries. To distribute reads between members with -higher latencies, pass an options array to the ``MongoDB\Client`` constructor that -sets the ``localThresholdMS`` option. - -The following example specifies a local threshold of 35 milliseconds: - -.. literalinclude:: /includes/databases-collections/databases-collections.php - :language: php - :dedent: - :start-after: start-local-threshold - :end-before: end-local-threshold - -In the preceding example, the {+php-library+} distributes reads among matching members -within 35 milliseconds of the closest member's ping time. - -.. note:: - - The {+php-library+} 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. +To learn more about setting a read preference, read concern, and write concern, +see the :ref:`php-read-write-pref` guide. API Documentation ----------------- diff --git a/source/includes/read-write-pref.php b/source/includes/read-write-pref.php new file mode 100644 index 00000000..9c0c8ed9 --- /dev/null +++ b/source/includes/read-write-pref.php @@ -0,0 +1,93 @@ + 'secondary', + 'readConcernLevel' => 'local', + 'w' => '2', +]; + +$client = new Client('mongodb://localhost:27017', $clientOptions); +// end-client-settings + +// start-client-settings-uri +$uri = 'mongodb://localhost:27017/?readPreference=secondary&readConcernLevel=local&w=2'; +$client = new Client($uri); +// end-client-settings-uri + +// start-session-settings +$sessionOptions = [ + 'readPreference' => new ReadPreference(ReadPreference::PRIMARY_PREFERRED), + 'readConcern' => new ReadConcern(ReadConcern::LOCAL), + 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY), +]; + +$session = $client->startSession($sessionOptions); +// end-session-settings + +// start-transaction-settings +$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 +$db = $client->selectDatabase('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 +$collection = $client->selectCollection('test_database', '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 +$readPreference = new ReadPreference( + ReadPreference::RP_SECONDARY, + [ + ['dc' => 'ny'], + ['dc' => 'sf'], + [], + ], +); + +$db = $client->selectDatabase( + 'test_database', + ['readPreference' => $readPreference], +); + +// end-tag-set + +// Instructs the library to distribute reads between members within 35 milliseconds +// of the closest member's ping time +// start-local-threshold +$options = [ + 'replicaSet' => 'repl0', + 'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED), + 'localThresholdMS' => 35, +]; + +$client = new Client('mongodb://localhost:27017', [], $options); +// end-local-threshold diff --git a/source/index.txt b/source/index.txt index 0a589f6e..89e32579 100644 --- a/source/index.txt +++ b/source/index.txt @@ -17,6 +17,7 @@ MongoDB PHP Library /aggregation /indexes /security + /read-write-pref /tutorial /upgrade /reference diff --git a/source/read-write-pref.txt b/source/read-write-pref.txt new file mode 100644 index 00000000..fd324f9d --- /dev/null +++ b/source/read-write-pref.txt @@ -0,0 +1,288 @@ +.. _php-read-write-pref: + +=============================================== +Specify How CRUD Operations Run on Replica Sets +=============================================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: 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 configure **write concern**, **read concern**, +and **read preference** options to modify the way that the {+php-library+} 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 inherited from the client. + +These options allow you to customize the causal consistency and availability of the data +in your replica sets. To see a full list of read preference, read concern, and write concern +options, see the following guides in the {+mdb-server+} manual: + +- :manual:`Read Preference ` +- :manual:`Read Concern ` +- :manual:`Write Concern ` + +.. _php-read-write-config: + +Configure Read and Write Operations +----------------------------------- + +You can control how the library routes read operations by setting a read preference. +You can also control how the library waits for acknowledgment of read and write operations +on a replica set by setting read and write concerns. + +This section shows how to configure the read preference, read concern, and write +concern at various levels by passing an options array parameter to any one of the +following methods: + +- :ref:`MongoDB\Client::__construct() `: Configures client-level + settings +- :ref:`MongoDB\Client::startSession() `: Configures session-level + settings +- :ref:`MongoDB\Driver\Session::startTransaction() `: + Configures transaction-level settings +- :ref:`MongoDB\Client::selectDatabase() `: Configures + database-level settings +- :ref:`MongoDB\Client::selectCollection() `: Configures + collection-level settings + +.. _php-read-write-client: + +Client Configuration +~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a ``MongoDB\Client`` instance by passing an array 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/read-write-pref.php + :language: php + :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 ``MongoDB\Client`` constructor: + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-client-settings-uri + :end-before: end-client-settings-uri + +.. note:: + + The ``readPreference``, ``readConcernLevel``, and ``w`` client options accept + string values. When configuring read and write settings at any other level, + you must assign values of type ``MongoDB\Driver\ReadPreference``, + ``MongoDB\Driver\ReadConcern``, and ``MongoDB\Driver\WriteConcern`` to the corresponding + options. + +.. _php-read-write-session: + +Session Configuration +~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a session by passing an array 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/read-write-pref.php + :language: php + :dedent: + :start-after: start-session-settings + :end-before: end-session-settings + +.. _php-read-write-transaction: + +Transaction Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a transaction by passing an array 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/read-write-pref.php + :language: php + :dedent: + :start-after: start-transaction-settings + :end-before: end-transaction-settings + +.. _php-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 an options +array to the ``selectDatabase()`` 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/read-write-pref.php + :language: php + :dedent: + :start-after: start-database-settings + :end-before: end-database-settings + +.. _php-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 an options +array to the ``selectCollection()`` 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: Requests no acknowledgment of the write operation + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-collection-settings + :end-before: end-collection-settings + +.. _php-read-write-advanced: + +Advanced Read Configurations +---------------------------- + +This section shows how to further customize your read operation +settings in the following ways: + +- :ref:`Apply a tag set ` +- :ref:`Specify a local threshold ` + +.. _php-tag-sets: + +Tag Sets +~~~~~~~~ + +The {+mdb-server+} allows you to 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 {+php-library+} ignores tags when choosing a member +to read from. To instruct the {+php-library+} to prefer certain tags, +pass them as a parameter to your ``MongoDB\Driver\ReadPreference`` class +constructor. Then, set the ``MongoDB\Driver\ReadPreference`` object as +the value of the ``readPreference`` database option. + +Suppose you are connected to a replica set that contains members hosted +at multiple data centers across the United States. 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/read-write-pref.php + :language: php + :dedent: + :start-after: start-tag-set + :end-before: end-tag-set + +.. _php-local-threshold: + +Local Threshold +~~~~~~~~~~~~~~~ + +If multiple replica-set members match the read preference and tag sets you specify, +the {+php-library+} reads from the nearest replica-set members, chosen according to +their ping time. + +By default, the library uses only members whose ping times are within 15 milliseconds +of the nearest member for queries. To distribute reads between members with +higher latencies, pass an options array to the ``MongoDB\Client`` constructor that +sets the ``localThresholdMS`` option. + +The following example specifies a local threshold of 35 milliseconds: + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-local-threshold + :end-before: end-local-threshold + +In the preceding example, the {+php-library+} distributes reads among matching members +within 35 milliseconds of the closest member's ping time. + +.. note:: + + The {+php-library+} 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. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following library API documentation: + +- :phpmethod:`MongoDB\Client::__construct()` +- :phpmethod:`MongoDB\Client::startSession()` +- :phpmethod:`MongoDB\Client::selectDatabase()` +- :phpmethod:`MongoDB\Client::selectCollection()` + +To learn more about the ``startTransaction()`` method, see :php:`MongoDB\Driver\Session::startTransaction() +` in the extension API documentation.