Docs HomeMongoDB Manual

Read Concern读取关注

The readConcern option allows you to control the consistency and isolation properties of the data read from replica sets and replica set shards.readConcern选项允许您控制从副本集和副本集分片读取的数据的一致性和隔离属性。

Through the effective use of write concerns and read concerns, you can adjust the level of consistency and availability guarantees as appropriate, such as waiting for stronger consistency guarantees, or loosening consistency requirements to provide higher availability.通过有效利用写入关注和读取关注,您可以适当调整一致性和可用性保证的级别,例如等待更强的一致性保证,或放松一致性要求以提供更高的可用性。

MongoDB drivers updated for MongoDB 3.2 or later support specifying read concern.为MongoDB 3.2或更高版本更新的MongoDB驱动程序支持指定读取关注。

Starting in MongoDB 4.4, replica sets and sharded clusters support setting a global default read concern. 从MongoDB 4.4开始,副本集和分片集群支持设置全局默认读取关注。Operations which do not specify an explicit read concern inherit the global default read concern settings. 未指定显式读取关注的操作将继承全局默认读取关注设置。See setDefaultRWConcern for more information.有关更多信息,请参阅setDefaultRWConcern

Read Concern Levels读取关注级别

The following read concern levels are available:以下读取关注级别可用:

levelDescription描述
"local"The query returns data from the instance with no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).查询从实例返回数据,但不能保证数据已写入大多数副本集成员(即可能被回滚)。
Default for reads against the primary and secondaries.针对主和辅助的默认读取。
Availability:可用性: Read concern "local" is available for use with or without causally consistent sessions and transactions.读取关注"local"可用于或不用于因果一致的会话和事务。
For more information, see the "local" reference page. 有关更多信息,请参阅"local"参考页。
"available"The query returns data from the instance with no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).查询从实例返回数据,但不能保证数据已写入大多数副本集成员(即可能被回滚)。
Availability:可用性: Read concern "available" is unavailable for use with causally consistent sessions and transactions.读取关注"available"不可用于因果一致的会话和事务。
For sharded clusters, "available" read concern provides the lowest latency reads possible among the various read concerns. 对于分片集群,"available"读取关注在各种读取关注中提供了尽可能低的延迟读取。However, this comes at the expense of consistency as "available" read concern can return orphaned documents when reading from a sharded collection. 然而,这是以牺牲一致性为代价的,因为"available"读取关注在从分片集合读取时可能会返回孤立文档To avoid the risk of returning orphaned documents when reading from sharded collections, use a different read concern such as read concern "local".为了避免从分片集合中读取时返回孤立文档的风险,请使用不同的读取关注,例如读取关注"local"
For more information, see the "available" reference page. 有关更多信息,请参阅"available"参考页。
"majority"The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.该查询返回大多数副本集成员已确认的数据。读取操作返回的文档是持久的,即使在失败的情况下也是如此。
To fulfill read concern "majority", the replica set member returns data from its in-memory view of the data at the majority-commit point. 为了实现读取关注“多数”,副本集成员从多数提交点的数据的内存视图中返回数据。As such, read concern "majority" is comparable in performance cost to other read concerns.因此,读取关注"majority"在性能成本上与其他读取关注相当。
Availability:可用性:
Read concern "majority" is available for use with or without causally consistent sessions and transactions.读取关注"majority"可在具有或不具有因果一致会话和事务的情况下使用。
Requirements:要求: To use read concern level of "majority", replica sets must use WiredTiger storage engine.要使用"majority"读取关注级别,副本集必须使用WiredTiger存储引擎
Note
For operations in multi-document transactions, read concern "majority" provides its guarantees only if the transaction commits with write concern "majority". 对于多文档事务中的操作,只有当事务以写关注"majority"提交时,读关注"majority"才提供其保证。Otherwise, the "majority" read concern provides no guarantees about the data read in transactions. 否则,"majority"读取关注无法保证事务中读取的数据。
For more information, see the "majority" reference page. 有关更多信息,请参阅"majority"参考页。
"linearizable"The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. 查询返回的数据反映了在读取操作开始之前完成的所有成功的多数确认写入。The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.在返回结果之前,查询可以等待并发执行写入以传播到大多数副本集成员。
If a majority of your replica set members crash and restart after the read operation, documents returned by the read operation are durable if writeConcernMajorityJournalDefault is set to the default state of true.如果大多数副本集成员在读取操作后崩溃并重新启动,则如果writeConcernMajorityJournalDefault设置为默认状态true,则读取操作返回的文档是持久的。
With writeConcernMajorityJournalDefault set to false, MongoDB does not wait for w: "majority" writes to be written to the on-disk journal before acknowledging the writes. writeConcernMajorityJournalDefault设置为false的情况下,MongoDB不会等待w: "majority"写入到磁盘日志中,然后再确认写入。As such, "majority" write operations could possibly roll back in the event of a transient loss (e.g. crash and restart) of a majority of nodes in a given replica set. 因此,在给定副本集中的大多数节点发生瞬时丢失(例如崩溃和重新启动)的情况下,"majority"写入操作可能会回滚。
Availability:可用性:
  • Read concern "linearizable" is unavailable for use with causally consistent sessions and transactions.读取关注"linearizable"不可用于因果一致的会话和事务。
  • You can specify linearizable read concern for read operations on the primary only.您可以仅在primary上为读取操作指定可线性化的读取关注。
You cannot use the $out or the $merge stage in conjunction with read concern "linearizable". 不能将$out$merge阶段与读取关注"linearizable"一起使用。That is, if you specify "linearizable" read concern for db.collection.aggregate(), you cannot include either stages in the pipeline.也就是说,如果为db.collection.aggregate()指定了"linearizable"读取关注,则不能在管道中包含这两个阶段。
Requirements:要求: Linearizable read concern guarantees only apply if read operations specify a query filter that uniquely identifies a single document. 只有当读取操作指定了唯一标识单个文档的查询筛选器时,线性化读取关注保证才适用。
Tip
Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable. 在大多数数据承载成员不可用的情况下,始终将maxTimeMS与线性化读取关注一起使用。maxTimeMS ensures that the operation does not block indefinitely and instead ensures that the operation returns an error if the read concern cannot be fulfilled. maxTimeMS确保操作不会无限期阻塞,而是确保在无法满足读取关注时操作返回错误。
For more information, see the "linearizable" reference page. 有关更多信息,请参阅"linearizable" 参考页。
"snapshot"A query with read concern "snapshot" returns majority-committed data as it appears across shards from a specific single point in time in the recent past. 带有读取关注"snapshot"的查询返回最近某个特定时间点的分片中出现的多数提交数据。Read concern "snapshot" provides its guarantees only if the transaction commits with write concern "majority". 只有当事务以写入关注"majority"提交时,读取关注"snapshot"才提供其保证。
If a transaction is not part of a causally consistent session, upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.如果事务不是因果一致会话的一部分,则在事务提交时,写入关注为"majority",则保证事务操作已从多数提交数据的快照中读取。
If a transaction is part of a causally consistent session, upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data that provides causal consistency with the operation immediately preceding the transaction start.如果事务是因果一致会话的一部分,则在事务提交时,写入关注为"majority",则保证事务操作已从多数提交数据的快照中读取,该快照提供了与事务启动前操作的因果一致性。
Availability:可用性:
Read concern "snapshot" is available for 读取关注"snapshot"可用于
  • All read operations inside multi-document transactions with the read concern set at the transaction level.在事务级别设置了读取关注的多文档事务中的所有读取操作。
  • The following methods outside of multi-document transactions:多文档事务处理之外的以下方法: All other read operations prohibit "snapshot".所有其他读取操作都禁止"snapshot"

Regardless of the read concern level, the most recent data on a node may not reflect the most recent version of the data in the system.无论读取关注级别如何,节点上的最新数据都可能无法反映系统中数据的最新版本。

For more information on each read concern level, see:有关每个读取关注级别的更多信息,请参阅:

readConcern Support支持

Read Concern Option读取关注选项

For operations not in multi-document transactions, you can specify a readConcern level as an option to commands and methods that support read concern:对于不在多文档事务中的操作,可以指定readConcern级别作为支持读取关注的命令和方法的选项:

readConcern: { level: <level> }

To specify the read concern level for mongosh method db.collection.find(), use the cursor.readConcern() method:要指定mongosh方法db.collection.find()的读取关注级别,请使用cursor.readConcern()方法:

db.collection.find().readConcern(<level>)

Transactions and Available Read Concerns事务和可用读取关注

For multi-document transactions, you set the read concern at the transaction level, not at the individual operation level. 对于多文档事务,您可以在事务级别设置读取关注,而不是在单个操作级别。The operations in the transaction will use the transaction-level read concern. 事务中的操作将使用事务级别的读取关注。Any read concern set at the collection and database level is ignored inside the transaction. 在集合和数据库级别设置的任何读取关注在事务内部都将被忽略。If the transaction-level read concern is explicitly specified, the client level read concern is also ignored inside the transaction.如果显式指定了事务级别的读取关注,那么在事务内部也会忽略客户端级别的读取关心点。

Important

Do not explicitly set the read concern for the individual operations. 不要为单个操作显式设置读取关注。To set the read concern for transactions, see Read Concern/Write Concern/Read Preference.要设置事务的读取关注,请参阅读取关注/写入关注/读取首选项

You can set the read concern at the transaction start:您可以在事务开始时设置读取关注:

  • For multi-document transaction, the following read concern levels are available:对于多文档事务,可以使用以下读取关注级别:

  • Write commands that are part of a multi-document transactions can support the transaction-level read concern.作为多文档事务一部分的写入命令可以支持事务级别的读取关注。
  • Starting in MongoDB 4.4, you can create collections and indexes inside a transaction. 从MongoDB 4.4开始,您可以在事务中创建集合和索引If explicitly creating a collection or an index, the transaction must use read concern "local". 如果显式创建集合或索引,则事务必须使用读取关注"local"Implicit creation of a collection can use any of the read concerns available for transactions.隐式创建集合可以使用任何可用于事务的读取关注。

If unspecified at the transaction start, transactions use the session-level read concern or, if that is unset, the client-level read concern.如果在事务开始时未指定,则事务将使用会话级读取关注,如果未设置,则使用客户端级读取关注。

For more information, see Transaction Read Concern.有关更多信息,请参阅事务读取关注

Causally Consistent Sessions and Available Read Concerns因果一致的会话和可用的阅读取关注

For operations in a causally consistent session, "local", "majority", and "snapshot" levels are available. However, to guarantee causal consistency, you must use "majority". 对于因果一致会话中的操作,可以使用"local""majority""snapshot"级别。但是,为了保证因果关系的一致性,必须使用"majority"For details, see Causal Consistency.有关详细信息,请参阅因果一致性

Operations That Support Read Concern支持读取关注的操作

The following operations support read concern:以下操作支持读取关注:

Important

To set read concern for operations in a transaction, you set the read concern at the transaction level, not at the individual operation level. 要为事务中的操作设置读取关注,请在事务级别设置读取关注,而不是在单个操作级别。Do not explicitly set the read concern for the individual operations in a transaction. 不要为事务中的各个操作显式设置读取关注。For more information, see Transactions and Read Concern.有关更多信息,请参阅事务和读取关注

Command/Method命令/方法"local""available""majority""snapshot" [3]"linearizable"
count
distinct[2]
find
db.collection.find() via cursor.readConcern()
getMore
aggregate db.collection.aggregate()[6]
Session.startTransaction()
[1] You cannot use the $out or the $merge stage in conjunction with read concern "linearizable". 不能将$out$merge阶段与读取关注"linearizable"一起使用。That is, if you specify "linearizable" read concern for db.collection.aggregate(), you cannot include either stages in the pipeline.也就是说,如果为db.collection.aggregate()指定了"linearizable"读取关注,则不能在管道中包含这两个阶段。
[2] Read concern "snapshot" is available only for certain read operations and for multi-document transactions. 读取关注"snapshot"仅适用于某些读取操作和多文档事务。In a transaction, you cannot use the distinct command or its helpers on a sharded collection.在事务中,不能在分片集合上使用distinct命令或其助手。

The following write operations can also accept a read concern if part of a multi-document transaction:如果是多文档事务的一部分,则以下写入操作也可以接受读取关注:

Important

To set read concern for operations in a transaction, you set the read concern at the transaction level, not at the individual operation level.要为事务中的操作设置读取关注,请在事务级别设置读取关注,而不是在单个操作级别。

Command命令"local""available""majority""snapshot" [3]"linearizable"
delete
db.collection.deleteOne()
db.collection.deleteMany()
db.collection.remove()
findAndModify
db.collection.findAndModify()
db.collection.findOneAndDelete()
db.collection.findOneAndReplace()
db.collection.findOneAndUpdate()
insert
db.collection.insertOne()
db.collection.insertMany()
update
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
create
db.createCollection()
(Requires fCV 4.4 or greater)
createIndexes
db.collection.createIndex()
db.collection.createIndexes()
(Requires fCV 4.4 or greater)
[3](1, 2) Read concern "snapshot" is available only for certain read operations and multi-document transactions. 读取关注"snapshot"仅适用于某些读取操作和多文档事务。For transactions, you set the read concern at the transaction level. 对于事务,您可以在事务级别设置读取关注。The transaction operations that support "snapshot" correspond to the CRUD operations available in transactions. 支持"snapshot"的事务操作对应于事务中可用的CRUD操作。For more information, see Transactions and Read Concern.有关更多信息,请参阅事务和读取关注

Read Concern not Supported on local Databaselocal数据库不支持读取关注

The local database does not support read concerns. local数据库不支持读取关注。MongoDB silently ignores any configured read concern for an operation on a collection in the local database.MongoDB静默地忽略本地数据库中集合上操作的任何配置的读取关注。

Considerations注意事项

Read Your Own Writes读取自己的写入

Changed in version 3.63.6版更改.

Starting in MongoDB 3.6, you can use causally consistent sessions to read your own writes, if the writes request acknowledgement.从MongoDB 3.6开始,如果写入请求确认,您可以使用因果一致会话来读取自己的写入。

Prior to MongoDB 3.6, in order to read your own writes you must issue your write operation with { w: "majority" } write concern, and then issue your read operation with primary read preference, and either "majority" or "linearizable" read concern.在MongoDB 3.6之前,为了读取您自己的写入,您必须发出具有{ w: "majority" }写入关注的写入操作,然后发出具有primary读取偏好的读取操作,以及"majority""linearizable"读取关注。

Real Time Order实时排序

Combined with "majority" write concern, "linearizable" read concern enables multiple threads to perform reads and writes on a single document as if a single thread performed these operations in real time; that is, the corresponding schedule for these reads and writes is considered linearizable."majority"写入关注相结合,"linearizable"读取关注使多个线程能够对单个文档执行读写操作,就好像单个线程实时执行这些操作一样;也就是说,这些读取和写入的相应时间表被认为是线性的。

Performance Comparisons性能比较

Unlike "majority", "linearizable" read concern confirms with secondary members that the read operation is reading from a primary that is capable of confirming writes with { w: "majority" } write concern. "majority"不同,"linearizable"读取关注向次要成员确认读取操作是从能够通过{ w: "majority" }写入关注确认写入的主要成员读取。[4] As such, reads with linearizable read concern may be significantly slower than reads with "majority" or "local" read concerns.因此,具有线性化阅读取关注的阅读可能比具有"majority""local"阅读取关注的读取慢得多。

Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable. 在大多数数据承载成员不可用的情况下,始终将maxTimeMS与线性化读取关注一起使用。maxTimeMS ensures that the operation does not block indefinitely and instead ensures that the operation returns an error if the read concern cannot be fulfilled.maxTimeMS确保操作不会无限期阻塞,而是确保在无法满足读取关注时操作返回错误。

For example:例如:

db.restaurants.find( { _id: 5 } ).readConcern("linearizable").maxTimeMS(10000)

db.runCommand( {
find: "restaurants",
filter: { _id: 5 },
readConcern: { level: "linearizable" },
maxTimeMS: 10000
} )
[4] 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的新写入最终会回滚。

Read Operations and 读取操作和afterClusterTime

MongoDB 3.6 introduces support for causally consistent sessions. MongoDB 3.6引入了对因果一致会话的支持。For read operations associated with causally consistent session, MongoDB 3.6 introduces the afterClusterTime read concern option to be set automatically by the drivers for operations associated with causally consistent sessions.对于与原因一致会话相关的读取操作,MongoDB 3.6引入了afterClusterTime读取关注选项,由驱动程序为与原因一致的会话相关的操作自动设置。

Important

Do not manually set afterClusterTime for a read operation. MongoDB drivers set this value automatically for operations associated with causally consistent sessions. 不要为读取操作手动设置afterClusterTime。MongoDB驱动程序为与因果一致会话相关联的操作自动设置此值。However, you can advance the operation time and the cluster time for the session, such as to be consistent with the operations of another client session. 但是,您可以提前会话的操作时间和集群时间,以便与另一个客户端会话的操作保持一致。For an example, see Examples.有关示例,请参阅示例

Note

It is not possible to specify atClusterTime in conjunction with afterClusterTime. 不能将atClusterTimeafterClusterTime一起指定。To use atClusterTime with read concern "snapshot" you have to disable causally consistent sessions.要将atClusterTime与读取关注"snapshot"一起使用,必须禁用因为一致性会话

To satisfy a read request with an afterClusterTime value of T, a mongod must perform the request after its oplog reaches time T. 要满足afterClusterTime值为T的读取请求,mongod必须在其oplog达到时间T后执行该请求。If its oplog has not reached time T, the mongod must wait to service the request.如果它的oplog还没有到达时间Tmongod必须等待为请求提供服务。

Read operations with a specified afterClusterTime return data that meet both the read concern level requirement and the specified afterClusterTime requirement.具有指定afterClusterTime的读取操作返回的数据同时满足读取关注级别要求和指定的afterClusterTime要求。

For read operations not associated with causally consistent sessions, afterClusterTime is unset.对于不与因果一致会话关联的读取操作,afterClusterTime是未设置的。

Read Concern Provenance读取关注来源

Starting in version 4.4, MongoDB tracks read concern provenance, which indicates the source of a particular read concern. 从4.4版本开始,MongoDB跟踪读取关注的来源,这表明了特定读取关注的provenanceYou may see provenance shown in the getLastError metrics, read concern error objects, and MongoDB logs.您可能会在getLastError度量、读取关注错误对象和MongoDB日志中看到provenance

The following table shows the possible read concern provenance values and their significance:下表显示了可能读取的关注provenance值及其重要性:

Provenance来源Description描述
clientSuppliedThe read concern was specified in the application.已在应用程序中指定读取关注。
customDefaultThe read concern originated from a custom defined default value. 读取关注源自自定义定义的默认值。See setDefaultRWConcern.请参阅setDefaultRWConcern
implicitDefaultThe read concern originated from the server in absence of all other read concern specifications.在没有所有其他读取关注规范的情况下,读取关注源自服务器。