Docs HomeMongoDB Manual

Read Preference读取首选项

Read preference describes how MongoDB clients route read operations to the members of a replica set.Read preference描述了MongoDB客户端如何将读取操作路由到副本集的成员。

Read operations to a replica set. Default read preference routes the read to the primary. Read preference of ``nearest`` routes the read to the nearest member.

By default, an application directs its read operations to the primary member in a replica set (i.e. read preference mode "primary"). But, clients can specify a read preference to send read operations to secondaries.默认情况下,应用程序将其读取操作定向到副本集中的主要成员(即读取首选项模式primary)。但是,客户端可以指定一个读取首选项来将读取操作发送到辅助设备。

Read preference consists of the read preference mode and optionally, a tag set list, the maxStalenessSeconds option, and the hedged read option. 读取首选项包括读取首选项模式和可选的标记集列表maxStalenessSeconds选项和对冲读取选项。Hedged read option is available for MongoDB 4.4+ sharded clusters for reads that use non-primary read preference.对于使用非主读取偏好的读取,MongoDB 4.4+分片集群提供了对冲读取选项。

The following table lists a brief summary of the read preference modes:下表列出了读取首选项模式的简要摘要:

Note

Starting in version 4.4, non-primary read preference modes support hedged read on sharded clusters.从4.4版本开始,非primary读取偏好模式支持在分片集群上进行对冲读取

Read Preference Mode读取首选项模式Description描述
primaryDefault mode. 默认模式。All operations read from the current replica set primary.从当前复制副本集primary读取的所有操作。
Multi-document transactions that contain read operations must use read preference primary. 包含读取操作的多文档事务必须使用读取首选项primaryAll operations in a given transaction must route to the same member. 给定事务中的所有操作都必须路由到同一成员。
primaryPreferredIn most situations, operations read from the primary but if it is unavailable, operations read from secondary members.在大多数情况下,操作从primary读取,但如果primary不可用,则操作从secondary成员读取。
Starting in version 4.4, primaryPreferred supports hedged reads on sharded clusters. 从版本4.4开始,primaryPreferred支持在分片集群上进行对冲读取
secondaryAll operations read from the secondary members of the replica set.从复制副本集的secondary成员读取的所有操作。
Starting in version 4.4, secondary supports hedged reads on sharded clusters. 从版本4.4开始,secondary支持在分片集群上进行对冲读取
secondaryPreferredOperations typically read data from secondary members of the replica set. 操作通常从复制副本集的secondary成员读取数据。If the replica set has only one single primary member and no other members, operations read data from the primary member.如果复制副本集只有一个primary成员,而没有其他成员,则操作会从主成员读取数据。
Starting in version 4.4, secondaryPreferred supports hedged reads on sharded clusters. 从版本4.4开始,secondaryPreferred支持在分片集群上进行对冲读取
nearestOperations read from a random eligible replica set member, irrespective of whether that member is a primary or secondary, based on a specified latency threshold. 根据指定的延迟阈值,从符合条件的随机副本集成员读取的操作,无论该成员是primary成员还是secondary成员。The operation considers the following when calculating latency: 在计算延迟时,操作会考虑以下因素: Starting in version 4.4, nearest supports hedged reads on sharded clusters and enables the hedged read option by default. 从版本4.4开始,nearest版本支持在分片集群上进行对冲读取,并默认启用对冲读取选项。

For detailed description of the read preference modes, see Read Preference Modes.有关读取首选项模式的详细说明,请参阅读取首选项

Behavior行为

  • All read preference modes except primary may return stale data because secondaries replicate operations from the primary in an asynchronous process. primary模式外的所有读取首选项模式都可能返回过时的数据,因为secondary模式在异步进程中从主模式复制操作。[1] Ensure that your application can tolerate stale data if you choose to use a non-primary mode.如果您选择使用非primary模式,请确保您的应用程序能够容忍过时的数据。
  • Read preference does not affect the visibility of data; i.e. clients can see the results of writes before they are acknowledged or have propagated to a majority of replica set members. 读取偏好不会影响数据的可见性;即,客户端可以在确认写入结果或将其传播到大多数副本集成员之前看到写入结果。For details, see Read Isolation, Consistency, and Recency.有关详细信息,请参阅读取隔离、一致性和最近性
  • Read preference does not affect causal consistency. 阅读偏好不会影响因果一致性The causal consistency guarantees provided by causally consistent sessions for read operations with "majority" read concern and write operations with "majority" write concern hold across all members of the MongoDB deployment.因果一致性会话为MongoDB部署的所有成员提供了因果一致性保证,用于"majority"读取关注的读取操作和"majority"写入关注的写入操作。

Read Preference Modes读取首选项模式

primary

All read operations use only the current replica set primary. 所有读取操作都只使用当前副本集primary[1] This is the default read mode. 这是默认的读取模式。If the primary is unavailable, read operations produce an error or throw an exception.如果主服务器不可用,则读取操作会产生错误或引发异常。

The primary read preference mode is not compatible with read preference modes that use tag set lists or maxStalenessSeconds. If you specify tag set lists or a maxStalenessSeconds value with primary, the driver will produce an error.primary读取首选项模式与使用标记集列表maxStalenessSeconds的读取首选项方式不兼容。如果使用primary指定标记集列表或maxStalenessSeconds值,则驱动程序将产生错误。

Multi-document transactions that contain read operations must use read preference primary. 包含读取操作的多文档事务必须使用读取首选项主。All operations in a given transaction must route to the same member.给定事务中的所有操作都必须路由到同一成员。

primaryPreferred

In most situations, operations read from the primary member of the set. 在大多数情况下,操作从集合的primary成员读取。However, if the primary is unavailable, as is the case during failover situations, operations read from secondary members that satisfy the read preference's maxStalenessSeconds and tag set lists.但是,如果主成员不可用(在故障转移情况下也是如此),则会从满足读取首选项的maxStalenessSeconds和标记集列表的secondary成员中读取操作。

When the primaryPreferred read preference includes a maxStalenessSeconds value and there is no primary from which to read, the client estimates how stale each secondary is by comparing the secondary's last write to that of the secondary with the most recent write. primaryPreferred读取首选项包含maxStalenessSeconds,并且没有要从中读取的主项时,客户端会通过比较辅助项的上次写入与辅助项的最近写入来估计每个辅助项的过时程度。The client then directs the read operation to a secondary whose estimated lag is less than or equal to maxStalenessSeconds.然后,客户端将读取操作定向到估计滞后小于或等于maxStalenessSeconds的辅助操作。

When the read preference includes a tag set list (an array of tag sets) and there is no primary from which to read, the client attempts to find secondary members with matching tags (trying the tag sets in order until a match is found). 当读取首选项包括标记集列表(标记集的数组),并且没有要从中读取的主成员时,客户端会尝试查找具有匹配标记的辅助成员(按顺序尝试标记集,直到找到匹配标记)。If matching secondaries are found, the client selects a random secondary from the nearest group of matching secondaries. 如果找到匹配的辅助设备,则客户端从最近的匹配辅助设备组中随机选择一个辅助设备。If no secondaries have matching tags, the read operation produces an error.如果没有辅助设备具有匹配的标记,则读取操作会产生错误。

When the read preference includes a maxStalenessSeconds value and a tag set list, the client filters by staleness first and then by the specified tags.当读取首选项包括maxStalenessSeconds值和标记集列表时,客户端会先按过时程度进行筛选,然后按指定的标记进行筛选。

Read operations using the primaryPreferred mode may return stale data. Use the maxStalenessSeconds option to avoid reading from secondaries that the client estimates are overly stale.使用primaryPreferred模式的读取操作可能会返回过时的数据。使用maxStalenessSeconds选项可以避免从辅助文件中读取到客户端估计的内容过于陈旧。

Note

Starting in version 4.4, primaryPreferred supports hedged reads on sharded clusters.从版本4.4开始,primaryPreferred支持在分片集群上进行对冲读取

secondary

Operations read only from the secondary members of the set. 操作仅从集合的secondary成员读取。If no secondaries are available, then this read operation produces an error or exception.如果没有可用的辅助,则此读取操作会产生错误或异常。

Most replica sets have at least one secondary, but there are situations where there may be no available secondary. 大多数复制副本集至少有一个辅助副本,但在某些情况下可能没有可用的辅助副本。For example, a replica set with a primary, a secondary, and an arbiter may not have any secondaries if a member is in recovering state or unavailable.例如,如果成员处于恢复状态或不可用,则具有primary、secondary和仲裁器的副本集可能不具有任何辅助副本。

When the secondary read preference includes a maxStalenessSeconds value, the client estimates how stale each secondary is by comparing the secondary's last write to that of the primary. secondary读取首选项包含maxStalenessSeconds时,客户端会通过将辅助的上次写入与主的上次写入进行比较来估计每个辅助的过时程度。The client then directs the read operation to a secondary whose estimated lag is less than or equal to maxStalenessSeconds. 然后,客户端将读取操作定向到估计滞后小于或等于maxStalenessSeconds的辅助操作。If there is no primary, the client uses the secondary with the most recent write for the comparison.如果没有主,则客户端使用具有最近写入的辅助进行比较。

When the read preference includes a tag set list (an array of tag sets), the client attempts to find secondary members with matching tags (trying the tag sets in order until a match is found). 当读取首选项包括标记集列表(标记集的数组)时,客户端会尝试查找具有匹配标记的辅助成员(按顺序尝试标记集,直到找到匹配的标记)。If matching secondaries are found, the client selects a random secondary from the nearest group of matching secondaries. 如果找到匹配的辅助设备,则客户端从最近的匹配辅助设备组中随机选择一个辅助设备。If no secondaries have matching tags, the read operation produces an error.如果没有辅助设备具有匹配的标记,则读取操作会产生错误。

When the read preference includes a maxStalenessSeconds value and a tag set list, the client filters by staleness first and then by the specified tags.当读取首选项包括maxStalenessSeconds值和标记集列表时,客户端会先按过时程度进行筛选,然后按指定的标记进行筛选。

Read operations using the secondary mode may return stale data. Use the maxStalenessSeconds option to avoid reading from secondaries that the client estimates are overly stale.使用secondary模式的读取操作可能会返回过时的数据。使用maxStalenessSeconds选项可以避免从辅助文件中读取到客户端估计的内容过于陈旧。

Note

Starting in version 4.4, secondary supports hedged reads on sharded clusters.从版本4.4开始,secondary支持在分片集群上进行对冲读取

secondaryPreferred

Operations typically read data from secondary members of the replica set. 操作通常从复制副本集的secondary成员读取数据。If the replica set has only one single primary member and no other members, operations read data from the primary member.如果复制副本集只有一个primary成员,而没有其他成员,则操作会从主成员读取数据。

When the secondaryPreferred read preference includes a maxStalenessSeconds value, the client estimates how stale each secondary is by comparing the secondary's last write to that of the primary. secondaryPreferred读取首选包含maxStalenessSeconds时,客户端会通过比较secondary的上次写入与primary的上次写入来估计每个secondary的过时程度。The client then directs the read operation to a secondary whose estimated lag is less than or equal to maxStalenessSeconds. 然后,客户端将读取操作定向到估计滞后小于或等于maxStalenessSeconds的辅助操作。If there is no primary, the client uses the secondary with the most recent write for the comparison. 如果没有主,则客户端使用具有最近写入的辅助进行比较。If there are no secondaries with estimated lag less than or equal to maxStalenessSeconds, the client directs the read operation to the replica set's primary.如果没有估计滞后时间小于或等于maxStalenessSeconds的辅助副本,则客户端会将读取操作定向到副本集的主副本。

When the read preference includes a tag set list (an array of tag sets), the client attempts to find secondary members with matching tags (trying the tag sets in order until a match is found). 当读取首选项包括标记集列表(标记集的数组)时,客户端会尝试查找具有匹配标记的辅助成员(按顺序尝试标记集,直到找到匹配的标记)。If matching secondaries are found, the client selects a random secondary from the nearest group of matching secondaries. 如果找到匹配的辅助设备,则客户端从最近的匹配辅助设备组中随机选择一个辅助设备。If no secondaries have matching tags, the client ignores tags and reads from the primary.如果没有辅助设备具有匹配的标记,则客户端将忽略标记并从主设备读取。

When the read preference includes a maxStalenessSeconds value and a tag set list, the client filters by staleness first and then by the specified tags.当读取首选项包括maxStalenessSeconds值和标记集列表时,客户端会先按过时程度进行筛选,然后按指定的标记进行筛选。

Read operations using the secondaryPreferred mode may return stale data. Use the maxStalenessSeconds option to avoid reading from secondaries that the client estimates are overly stale.使用secondaryPreferred模式的读取操作可能会返回过时的数据。使用maxStalenessSeconds选项可以避免从辅助文件中读取到客户端估计的内容过于陈旧。

Note

Starting in version 4.4, secondaryPreferred supports hedged reads on sharded clusters.从版本4.4开始,secondaryPreferred支持在分片集群上进行对冲读取

nearest

The driver reads from a member whose network latency falls within the acceptable latency window. 驱动程序从网络延迟在可接受延迟窗口内的成员读取。Reads in the nearest mode do not consider whether a member is a primary or secondary when routing read operations: primaries and secondaries are treated equivalently.在路由读取操作时,nearest模式下的读取不考虑成员是主成员还是辅助成员:primarysecondary被同等对待。

Set this mode to minimize the effect of network latency on read operations without preference for current or stale data.设置此模式可以最大限度地减少网络延迟对读取操作的影响,而不必首选当前或过时的数据。

When the read preference includes a maxStalenessSeconds value, the client estimates how stale each secondary is by comparing the secondary's last write to that of the primary, if available, or to the secondary with the most recent write if there is no primary. 当读取首选项包含maxStalenessSeconds时,客户端会通过比较辅助的上次写入与主的写入(如果可用),或者比较辅助的写入与最近的写入(如没有主的写入),来估计每个辅助的过时程度。The client will then filter out any secondary whose estimated lag is greater than maxStalenessSeconds and randomly direct the read to a remaining member (primary or secondary) whose network latency falls within the acceptable latency window.然后,客户端将筛选出任何估计延迟大于maxStalenessSeconds的辅助成员,并随机将读取定向到网络延迟在可接受延迟窗口内的剩余成员(主成员或辅助成员)。

If you specify a tag set list, the client attempts to find a replica set member that matches the specified tag set lists and directs reads to an arbitrary member from among the nearest group.如果指定了标记集列表,则客户端会尝试查找与指定标记集列表匹配的副本集成员,并将读取定向到最近组中的任意成员。

When the read preference includes a maxStalenessSeconds value and a tag set list, the client filters by staleness first and then by the specified tags. From the remaining mongod instances, the client then randomly directs the read to an instance that falls within the acceptable latency window. 当读取首选项包括maxStalenessSeconds值和标记集列表时,客户端会先按过时程度进行筛选,然后按指定的标记进行筛选。然后,客户端从剩余的mongod实例中随机将读取定向到位于可接受延迟窗口内的实例。The read preference member selection documentation describes the process in detail.已阅读的首选项成员选择文档详细描述了该过程。

Read operations using the nearest mode may return stale data. 使用nearest模式的读取操作可能会返回过时的数据。Use the maxStalenessSeconds option to avoid reading from secondaries that the client estimates are overly stale.使用maxStalenessSeconds选项可以避免从辅助文件中读取到客户端估计的内容过于陈旧。

Note

Starting in version 4.4, read preference nearest, by default, specifies the use of hedged reads for reads on a sharded cluster.从版本4.4开始,默认情况下,nearest的读取首选项指定在分片集群上使用对冲读取

Tip

See also: 另请参阅:

To learn about use cases for specific read preference settings, see Read Preference Use Cases.要了解特定读取首选项设置的用例,请参阅读取首选项用例

Configure Read Preference配置读取首选项

When using a MongoDB driver, you can specify the read preference using the driver's read preference API. 使用MongoDB驱动程序时,可以使用驱动程序的读取首选项API指定读取首选项。See the driver API documentation. 请参阅驱动程序API文档You can also set the read preference (except for the hedged read option) when connecting to the replica set or sharded cluster. 您还可以在连接到副本集或分片集群时设置读取首选项(对冲读取选项除外)。For an example, see connection string.有关示例,请参阅连接字符串

For a given read preference, the MongoDB drivers use the same member selection logic.对于给定的读取偏好,MongoDB驱动程序使用相同的成员选择逻辑

When using mongosh, see cursor.readPref() and Mongo.setReadPref().使用mongosh时,请参阅cursor.readPref()Mongo.setReadPref()

Read Preference and Transactions读取首选项和事务

Multi-document transactions that contain read operations must use read preference primary. 包含读取操作的多文档事务必须使用读取首选项主。All operations in a given transaction must route to the same member.给定事务中的所有操作都必须路由到同一成员。

Additional Considerations其他注意事项

For aggregation pipeline operations that include the $out or $merge stages, the pipeline runs on the primary member regardless of read preference setting.对于包含$out$merge阶段的聚合管道操作,无论读取首选项设置如何,管道都在primary成员上运行。

For mapReduce operations, only "inline" mapReduce operations that do not write data support read preference. 对于mapReduce操作,只有不写入数据的“内联”mapReduce运算支持读取首选项。Otherwise, mapReduce operations run on the primary member.否则,mapReduce操作将在primary成员上运行。

[1](1, 2) In some circumstances, two nodes in a replica set may transiently believe that they are the primary, but at most, one of them will be able to complete writes with { w: "majority" } write concern. 某些情况下,副本集中的两个节点可能会暂时认为它们是主节点,但最多其中一个节点能够完成具有{ w: "majority" }写入关注的写入。The node that can complete { w: "majority" } writes is the current primary, and the other node is a former primary that has not yet recognized its demotion, typically due to a network partition. 可以完成{ w: "majority" }写入的节点是当前主节点,而另一个节点是尚未识别其降级的前主节点,通常是由于网络分区When this occurs, clients that connect to the former primary may observe stale data despite having requested read preference primary, and new writes to the former primary will eventually roll back.当这种情况发生时,连接到前一个主服务器的客户端可能会观察到过时的数据,尽管请求了读取首选项主服务器,并且对前一个primary的新写入最终会回滚。