Definition定义
cursor.readPref(mode, tagSet)-
Important
mongosh
Method方法This page documents a本页记录了一种mongoshmethod. This is not the documentation for a language-specific driver, such as Node.js.mongosh方法。这不是针对特定语言驱动程序(如Node.js)的文档。For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档。Append将readPref()to a cursor to control how the client routes the query to members of the replica set.readPref()附加到游标,以控制客户端如何将查询路由到副本集的成员。Note
You must apply在从数据库检索任何文档之前,必须对游标应用readPref()to the cursor before retrieving any documents from the database.readPref()。
Parameters参数
mode |
| |
tagSet | array of documents |
|
readPref() does not support the Read Preference 不支持读取首选项的读取首选项maxStalenessSeconds option for read preference.maxStalenessSeconds选项。
Compatibility兼容性
This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Note
This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Examples示例
Specify Read Preference Mode指定读取首选项模式
The following operation uses the read preference mode to target the read to a secondary member.以下操作使用读取首选项mode将读取目标定位到次要成员。
db.collection.find({ }).readPref( "secondary")Specify Read Preference Tag Set指定读取首选项标记集
To target secondaries with specific tags, include both the mode and the tagSet array:要针对具有特定标签的secondary,请同时包含mode和tagSet数组:
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 secondary members with the 在二次选择过程中,MongoDB试图找到数据中心的datacenter: "B" tag first.datacenter: "B"标签优先。
If found, MongoDB limits the eligible secondaries to those with the如果找到,MongoDB将符合条件的secondary限制为具有数据中心的datacenter: "B"tag and ignores the remaining tags.datacenter: "B"标签,并忽略其余标签。If none are found, then, MongoDB tries to find secondary members with the如果没有找到,那么MongoDB会尝试找到带有"region": "West"tag."region": "West"标签的secondary成员。If found, MongoDB limits the eligible secondaries to those with the如果找到,MongoDB将符合条件的二级服务器限制为带有"region": "West"tag."region": "West"标签的服务器。If none are found, MongoDB uses any eligible secondaries.如果没有找到,MongoDB将使用任何符合条件的二级服务器。
See Order of Tag Matching for details.详见标签匹配顺序。