- Reference >
mongo
Shell Methods >- Cursor Methods >
- cursor.readPref()
cursor.readPref()¶
On this page
Definition¶
-
cursor.
readPref
(mode, tagSet, hedgeOptions)¶ mongo
Shell MethodThis page documents the
mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.Append
readPref()
to a cursor to control how the client routes the query to members of the replica set.Note
You must apply
readPref()
to the cursor before retrieving any documents from the database.
Parameters¶
Parameter | Type | Description |
---|---|---|
mode | string | One of the following read preference modes: |
tagSet | array of documents | Optional. A tag set used to target reads to
members with the specified tag(s). For details, see Read Preference Tag Sets. |
hedgeOptions | document | Optional. A document that specifies whether to enable the use of hedged reads.
The Hedged reads are available starting in MongoDB 4.4 for sharded
clusters. To use hedged reads, the Read preference New in version 4.4. |
cursor.setReadPref()
does not support the
Read Preference maxStalenessSeconds option for read
preference.
Examples¶
Specify Read Preference Mode¶
The following operation uses the read preference mode to target the read to a secondary member.
Specify Read Preference Tag Set¶
To target secondaries with specific tags, include both the mode and the tagSet array:
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.
- If found, MongoDB limits the eligible secondaries to those with the
See Order of Tag Matching for details.
See also
Specify Hedged Read¶
Starting in MongoDB 4.4 for sharded clusters, you can enable
hedged reads for non-primary read
preferences. To use hedged reads, the
mongos
must have enabled support
for hedged reads (the default) and the
non-primary
read preferences must
enable the use of hedged reads.
To target secondaries on 4.4+ sharded cluster using hedged reads, include both the mode and the hedgeOptions, as in the following examples:
Without a tag set
With a tag set