对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

读关注 (read concern) "snapshot"

在版本5.0中进行了更改。

具有读关注 "snapshot" 的查询会返回最近某个特定时间点跨分片出现的多数提交数据。仅当事务以写关注 "majority" 提交时,读关注 "snapshot" 才提供保证。

读关注 "snapshot" 可用于多文档事务,以及从 MongoDB 5.0 开始,多文档事务之外的某些读取操作。

  • 如果事务不是因果一致会话的一部分,则在以写关注 "majority" 提交事务时,保证已从多数提交数据的快照中读取事务操作。

  • 如果事务是因果一致会话的一部分,则在以写关注 "majority" 提交事务后,保证事务操作从多数提交数据的快照中读取,该快照与事务开始前立即执行的操作具有因果一致性。

重要

"snapshot" 读取只能在 minSnapshotHistoryWindowInSeconds 指定的时间段内执行。持续时间超过 minSnapshotHistoryWindowInSeconds 的读取操作可能会终止。

Outside of multi-document transactions, read concern "snapshot" is available on primaries and secondaries for the following read operations:

All other read commands prohibit "snapshot".

有关接受读关注的所有操作的列表,请参阅支持读关注的操作。

Multi-document transactions support read concern "snapshot" as well as "local", and "majority".

注意

您可以在事务级别设置读关注,而不是在单个操作级别。要为事务设置读关注,请参阅事务和读关注(read concern)。

Outside of multi-document transactions, reads with read concern "snapshot" support the optional parameter atClusterTime. The parameter atClusterTime allows you to specify the timestamp for the read. To satisfy a read request with a specified atClusterTime of T, the mongod performs the request based on the data available at time T. If the mongod has not yet reached time T in its oplog, it waits to service the request.

提示

如果您的读取指向滞后的副本集节点,则可以使用 maxTimeMS 来限定具有指定 atClusterTime 的读取的等待时间。maxTimeMS 确保操作不会无限期受阻,而是在 mongod 未能及时达到指定 atClusterTime 时返回错误。

您可以从 db.runCommand() 的响应或从 Session() 对象获取操作的 operationTimeclusterTime

The following command performs a find operation with read concern "snapshot" and specifies that the operation should read data from the snapshot at cluster time Timestamp(1613577600, 1).

db.runCommand( {
find: "restaurants",
filter: { _id: 5 },
readConcern: {
level: "snapshot",
atClusterTime: Timestamp(1613577600, 1)
},
} )

如果未提供参数 atClusterTime,则 mongos 或在单个成员副本中设置 mongod,选择最新的多数提交快照的时间戳作为 atClusterTime,并将其返回给客户端。

Outside of transactions, "snapshot" reads are guaranteed to read from majority-committed data.

  • The allowed values for atClusterTime depend on the minSnapshotHistoryWindowInSeconds parameter. minSnapshotHistoryWindowInSeconds is the minimum time window in seconds for which the storage engine keeps the snapshot history. If you specify an atClusterTime value older than the oldest snapshot retained according to minSnapshotHistoryWindowInSeconds, mongod returns an error.

  • If you perform a read operation with "snapshot" without specifying atClusterTime against a delayed replica set member, the returned majority-committed data could be stale. If you specify atClusterTime, the mongod waits for the specified timestamp instead of returning stale data, though the read may block or time out.

  • It is not possible to specify atClusterTime for "snapshot" inside of causally consistent sessions.

从MongoDB8.0 开始,您可以在固定大小集合上使用读关注(read concern)"snapshot"