Mongo.setReadPref()

Definition

  • Mongo.setReadPref(mode, tagSet)
  • Call the setReadPref() method on a Mongo connection object to control how the client willroute all queries to members of the replica set. [1]

Note

You must call Mongo.setReadPref() on the connection objectbefore retrieving documents using that connection to use that readpreference.

[1]To apply a read preference for a specific query or queries, you canapply cursor.readPref() to a cursor before iteration. Seecursor.readPref() for details.

Parameters

ParameterTypeDescription
modestringOne of the following read preference modes: primary,primaryPreferred, secondary,secondaryPreferred, or nearest
tagSetarray of documentsOptional. A tag set used to target reads tomembers with the specified tag(s). tagSet is not availableif using read preference mode primary.For details, see Tag Set.

Mongo.setReadPref() does not support themaxStalenessSeconds option for readpreference.

Examples

The following operation uses the read preference mode to target theread to a secondary member.

  1. db.getMongo().setReadPref('secondary')

To target secondaries with specific tags, include the tag set array:

  1. db.getMongo().setReadPref(
  2. "secondary",
  3. [
  4. { "datacenter": "B" }, // First, try matching by the datacenter tag
  5. { "region": "West"}, // If not found, then try matching by the region tag
  6. { } // If not found, then use the empty document to match all eligible members
  7. ]
  8. )

During the secondary selection process, MongoDB tries to find secondarymembers with the datacenter: "B" tag first.

  • If found, MongoDB limits the eligible secondaries to those with thedatacenter: "B" tag and ignores the remaining tags.
  • If none are found, then, MongoDB tries to find secondary members withthe "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 Order of Tag Matching for details.

See also

Configure Replica Set Tag Sets