Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
112 lines (74 sloc) 2.97 KB
===================
Mongo.setReadPref()
===================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. method:: Mongo.setReadPref(mode, tagSet)
Call the :method:`~Mongo.setReadPref()` method on a :method:`Mongo
<db.getMongo()>` connection object to control how the client will
route all queries to members of the replica set. [#specificqueries]_
.. note::
You must call :method:`Mongo.setReadPref()` on the connection object
before retrieving documents using that connection to use that read
preference.
.. [#specificqueries]
To apply a read preference for a specific query or queries, you can
apply :method:`cursor.readPref()` to a cursor before iteration. See
:method:`cursor.readPref()` for details.
Parameters
~~~~~~~~~~
.. list-table::
:header-rows: 1
:widths: 20 20 80
* - Parameter
- Type
- Description
* - :ref:`mode <mongo-setReadPref-mode>`
- string
- .. _mongo-setReadPref-mode:
One of the following :term:`read preference` modes: :readmode:`primary`,
:readmode:`primaryPreferred`, :readmode:`secondary`,
:readmode:`secondaryPreferred`, or :readmode:`nearest`
* - ``tagSet``
- array of documents
- Optional. A :ref:`tag set
<replica-set-read-preference-tag-sets>` used to target reads to
members with the specified tag(s). ``tagSet`` is not available
if using read preference mode :readmode:`primary`.
For details, see :ref:`replica-set-read-preference-tag-sets`.
:method:`Mongo.setReadPref()` does not support the
:ref:`replica-set-read-preference-max-staleness` option for read
preference.
Examples
--------
The following operation uses the read preference mode to target the
read to a secondary member.
.. code-block:: javascript
db.getMongo().setReadPref('secondary')
To target secondaries with specific tags, include the tag set array:
.. code-block:: javascript
db.getMongo().setReadPref(
"secondary",
[
{ "datacenter": "B" }, // First, try matching by the datacenter tag
{ "region": "West"}, // If not found, then try matching by the region tag
{ } // If not found, then use the empty document to match all eligible members
]
)
During the secondary selection process, MongoDB tries to find secondary
members with the ``datacenter: "B"`` tag first.
- If found, MongoDB limits the eligible secondaries to those with the
``datacenter: "B"`` tag and ignores the remaining tags.
- If none are found, then, MongoDB tries to find secondary members with
the ``"region": "West"`` tag.
- If found, MongoDB limits the eligible secondaries to those with the
``"region": "West"`` tag.
- If none are found, MongoDB uses any eligible secondaries.
See :ref:`read-pref-order-matching` for details.
.. seealso:: :doc:`/tutorial/configure-replica-set-tag-sets`
You can’t perform that action at this time.