cursor.readPref()
Definition
mongo
Shell Method
This page documents the mongo
shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.
Append readPref()
to a cursor tocontrol how the client routes the query to membersof the replica set.
Note
You must apply readPref()
to the cursor before retrievingany documents from the database.
Parameters
Parameter | Type | Description |
---|---|---|
mode | string | One of the following read preference modes: primary ,primaryPreferred , secondary ,secondaryPreferred , or nearest |
tagSet | array of documents | Optional. A tag set used to target reads tomembers with the specified tag(s). tagSet is not availableif using primary .For details, see Tag Set. |
cursor.setReadPref()
does not support themaxStalenessSeconds option for readpreference.
Example
The following operation uses the read preference mode to target theread to a secondary member.
- db.collection.find({ }).readPref( "secondary")
To target secondaries with specific tags, include the tag set array:
- db.collection.find({ }).readPref(
- "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 secondarymembers 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 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.
- If found, MongoDB limits the eligible secondaries to those with the
See Order of Tag Matching for details.
See also