On this page本页内容
Mongo.setReadPref(mode, tagSet, hedgeOptions)¶Call the setReadPref() method on a Mongo connection object to control how the client will route all queries to members of the replica set. [1]
Note
You must call Mongo.setReadPref() on the connection object before retrieving documents using that connection to use that read preference.
| [1] | To apply a read preference for a specific query or queries, you can apply cursor.readPref() to a cursor before iteration. See cursor.readPref() for details. |
| 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
|
Mongo.setReadPref() does not support the Read Preference maxStalenessSeconds option for read preference.
The following operation sets the read preference mode to target the read to a secondary member. This implicitly allows reads from secondaries.
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.
datacenter: "B" tag and ignores the remaining tags."region": "West" tag."region": "West" tag.See Order of Tag Matching for details.
See also参阅
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: