Docs HomeMongoDB Manual

Write Concern写入关注事项

Write concern describes the level of acknowledgment requested from MongoDB for write operations to a standalone mongod or to Replica sets or to sharded clusters. 写入关注描述了MongoDB对独立mongod、复制集或分片集群的写操作请求的确认级别。In sharded clusters, mongos instances will pass the write concern on to the shards.在分片集群中,mongos实例将把写问题传递给分片。

Note

For multi-document transactions, you set the write concern at the transaction level, not at the individual operation level. Do not explicitly set the write concern for individual write operations in a transaction.对于多文档事务,您可以在事务级别设置写入关注点,而不是在单个操作级别。不要为事务中的单个写入操作显式设置写入问题。

If you specify a "majority" write concern for a multi-document transaction and the transaction fails to replicate to the calculated majority of replica set members, then the transaction may not immediately roll back on replica set members. The replica set will be eventually consistent. 如果为多文档事务指定了"majority"写入关注,而该事务未能复制到计算出的多数副本集成员,则该事务可能不会立即回滚到副本集成员。复制副本集最终将保持一致A transaction is always applied or rolled back on all replica set members.事务总是在所有复制集成员上应用或回滚。

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

Write Concern Specification写入关注规范

Write concern can include the following fields:写入关注可能包括以下字段:

{ w: <value>, j: <boolean>, wtimeout: <number> }
  • the w option to request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.w选项,用于请求确认写入操作已传播到指定数量的mongod实例或具有指定标记的mongod实例。

  • the j option to request acknowledgment that the write operation has been written to the on-disk journal, andj选项,用于请求确认写入操作已写入磁盘上的日志,以及

  • the wtimeout option to specify a time limit to prevent write operations from blocking indefinitely.wtimeout选项指定一个时间限制,以防止写操作无限期阻塞。

w Option选项

The w option requests acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.w选项请求确认写入操作已传播到指定数量的mongod实例或具有指定标记的mongod实例。

Using the w option, the following w: <value> write concerns are available:使用w选项,可以使用以下w: <value>写入关注:

ValueDescription描述
"majority"
Requests acknowledgment that write operations have been durably committed to the calculated majority of the data-bearing voting members (i.e. primary and secondaries with members[n].votes greater than 0). { w: "majority" } is the default write concern for most MongoDB deployments. See Implicit Default Write Concern.
For example, consider a replica set with 3 voting members, Primary-Secondary-Secondary (P-S-S). For this replica set, calculated majority is two, and the write must propagate to the primary and one secondary to acknowledge the write concern to the client.
Note
Hidden, delayed, and priority 0 members with members[n].votes greater than 0 can acknowledge "majority" write operations.
Delayed secondaries can return write acknowledgment no earlier than the configured secondaryDelaySecs.
After the write operation returns with a w: "majority" acknowledgment to the client, the client can read the result of that write with a "majority" readConcern.
If you specify a "majority" write concern for a multi-document transaction and the transaction fails to replicate to the calculated majority of replica set members, then the transaction may not immediately roll back on replica set members. The replica set will be eventually consistent. A transaction is always applied or rolled back on all replica set members.
See Acknowledgment Behavior for when mongod instances acknowledge the write.
<number>
Requests acknowledgment that the write operation has propagated to the specified number of mongod instances. 请求确认写入操作已传播到指定数量的mongod实例。For example:例如:
w: 1
Requests acknowledgment that the write operation has propagated to the standalone mongod or the primary in a replica set. Data can be rolled back if the primary steps down before the write operations have replicated to any of the secondaries.
w: 0
Requests no acknowledgment of the write operation. 不请求对写入操作的确认。However, w: 0 may return information about socket exceptions and networking errors to the application. Data can be rolled back if the primary steps down before the write operations have replicated to any of the secondaries.
If you specify w: 0 but include j: true, the j: true prevails to request acknowledgment from the standalone mongod or the primary of a replica set.
w greater than 1 requires acknowledgment from the primary and as many data-bearing secondaries as needed to meet the specified write concern. The secondaries do not need to be voting members to meet the write concern threshold.
For example, consider a 3-member replica set with a primary and 2 secondaries. Specifying w: 2 would require acknowledgment from the primary and one of the secondaries. Specifying w: 3 would require acknowledgment from the primary and both secondaries.
Note
Hidden, delayed, and priority 0 members can acknowledge w: <number> write operations.
Delayed secondaries can return write acknowledgment no earlier than the configured secondaryDelaySecs.
See Acknowledgment Behavior for when mongod instances acknowledge the write.
<custom write concern name>
Requests acknowledgment that the write operations have propagated to tagged members that satisfy the custom write concern defined in settings.getLastErrorModes. For an example, see Custom Multi-Datacenter Write Concerns.
Data can be rolled back if the custom write concern only requires acknowledgment from the primary and the primary steps down before the write operations have replicated to any of the secondaries.
See Acknowledgment Behavior for when mongod instances acknowledge the write.

j Option

The j option requests acknowledgment from MongoDB that the write operation has been written to the on-disk journal.

j
If j: true, requests acknowledgment that the mongod instances, as specified in the w: <value>, have written to the on-disk journal. j: true does not by itself guarantee that the write will not be rolled back due to replica set primary failover.
Changed in version 3.2: With j: true, MongoDB returns only after the requested number of members, including the primary, have written to the journal. Previously j: true write concern in a replica set only requires the primary to write to the journal, regardless of the w: <value> write concern.
Note

wtimeout

This option specifies a time limit, in milliseconds, for the write concern. wtimeout is only applicable for w values greater than 1.

wtimeout causes write operations to return with an error after the specified limit, even if the required write concern will eventually succeed. When these write operations return, MongoDB does not undo successful data modifications performed before the write concern exceeded the wtimeout time limit.

If you do not specify the wtimeout option and the level of write concern is unachievable, the write operation will block indefinitely. Specifying a wtimeout value of 0 is equivalent to a write concern without the wtimeout option.

Implicit Default Write Concern

Starting in MongoDB 5.0, the implicit default write concern is w: majority. However, special considerations are made for deployments containing arbiters:

  • The voting majority of a replica set is 1 plus half the number of voting members, rounded down. If the number of data-bearing voting members is not greater than the voting majority, the default write concern is { w: 1 }.

  • In all other scenarios, the default write concern is { w: "majority" }.

Specifically, MongoDB uses the following formula to determine the default write concern:

if [ (#arbiters > 0) AND (#non-arbiters <= majority(#voting-nodes)) ]
defaultWriteConcern = { w: 1 }
else
defaultWriteConcern = { w: "majority" }

For example, consider the following deployments and their respective default write concerns:

Non-ArbitersArbitersVoting NodesMajority of Voting NodesImplicit Default Write Concern
2132{ w: 1 }
4153{ w: "majority" }
  • In the first example:

    • There are 2 non-arbiters and 1 arbiter for a total of 3 voting nodes.

    • The majority of voting nodes (1 plus half of 3, rounded down) is 2.

    • The number of non-arbiters (2) is equal to the majority of voting nodes (2), resulting in an implicit write concern of { w: 1 }.

  • In the second example:

    • There are 4 non-arbiters and 1 arbiter for a total of 5 voting nodes.

    • The majority of voting nodes (1 plus half of 5, rounded down) is 3.

    • The number of non-arbiters (4) is greater than the majority of voting nodes (3), resulting in an implicit write concern of { w: "majority" }.

Acknowledgment Behavior

The w option and the j option determine when mongod instances acknowledge write operations.

Standalone

A standalone mongod acknowledges a write operation either after applying the write in memory or after writing to the on-disk journal. The following table lists the acknowledgment behavior for a standalone and the relevant write concerns:

j is unspecifiedj:truej:false
w: 1In memoryOn-disk journalIn memory
w: "majority"On-disk journal if running with journalingOn-disk journalIn memory
Note

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. 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.

Replica Sets

The value specified to w determines the number of replica set members that must acknowledge the write before returning success. For each eligible replica set member, the j option determines whether the member acknowledges writes after applying the write operation in memory or after writing to the on-disk journal.

w: "majority"

Any data-bearing voting member of the replica set can contribute to write acknowledgment of "majority" write operations.

The following table lists when the member can acknowledge the write based on the j value:

j is unspecifiedAcknowledgment depends on the value of writeConcernMajorityJournalDefault:
  • If true, acknowledgment requires writing operation to on-disk journal (j: true).
    writeConcernMajorityJournalDefault defaults to true
  • If false, acknowledgment requires writing operation in memory (j: false).
j: trueAcknowledgment requires writing operation to on-disk journal.
j: falseAcknowledgment requires writing operation in memory.
Note

For behavior details, see w: "majority" Behavior.

w: <number>

Any data-bearing member of the replica set can contribute to write acknowledgment of w: <number> write operations.

The following table lists when the member can acknowledge the write based on the j value:

j is unspecifiedAcknowledgment requires writing operation in memory (j: false).
j: trueAcknowledgment requires writing operation to on-disk journal.
j: falseAcknowledgment requires writing operation in memory.
Note

Hidden, delayed, and priority 0 members can acknowledge w: <number> write operations.

Delayed secondaries can return write acknowledgment no earlier than the configured secondaryDelaySecs.

Additional Information

Causally Consistent Sessions and Write Concerns

With causally consistent client sessions, the client sessions only guarantee causal consistency if:

  • the associated read operations use "majority" read concern, and

  • the associated write operations use "majority" write concern.

For details, see Causal Consistency.

w: "majority" Behavior

  • 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. 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.

  • Hidden, delayed, and priority 0 members with members[n].votes greater than 0 can acknowledge "majority" write operations.

    • Delayed secondaries can return write acknowledgment no earlier than the configured secondaryDelaySecs.

  • Starting in MongoDB 5.0, replica set members in the STARTUP2 state do not participate in write majorities.

Write Concern not Supported on local Database

The local database does not support write concerns. MongoDB silently ignores any configured write concern for an operation on a collection in the local database.

Calculating Majority for Write Concern

Tip

Starting in version 4.2.1, the rs.status() returns the writeMajorityCount field which contains the calculated majority number.

The majority for write concern "majority" is calculated as the smaller of the following values:

  • the majority of all voting members (including arbiters) vs.

  • the number of all data-bearing voting members.

Warning

In cases where the calculated majority number is equal to the number of all data-bearing voting members (such as with a 3-member Primary-Secondary-Arbiter deployment), write concern "majority" may time out or never be acknowledged if a data bearing voting member is down or unreachable. If possible, use a data-bearing voting member instead of an arbiter.

For example, consider:

  • A replica set with 3 voting members, Primary-Secondary-Secondary (P-S-S):

    • The majority of all voting members is 2.

    • The number of all data-bearing voting members is 3.

    The calculated majority is 2, the minimum of 2 and 3. The write must propagate to the primary and one of the secondaries to acknowledge the write concern "majority" to the client.
  • A replica set with 3 voting members, Primary-Secondary-Arbiter (P-S-A)

    • The majority of all voting members is 2.

    • The number of all data-bearing voting members is 2.

    The calculated majority is 2, the minimum of 2 and 2. Since the write can only be applied to data-bearing members, the write must propagate to the primary and the secondary to acknowledge the write concern "majority" to the client.
    Tip

    Avoid using a "majority" write concern with a (P-S-A) or other topologies that require all data-bearing voting members to be available to acknowledge the writes. Customers who want the durability guarantees of using a "majority" write concern should instead deploy a topology that does not require all data bearing voting members to be available (e.g. P-S-S).

Warning

Avoid deploying more than one arbiter in a replica set. See Concerns with Multiple Arbiters.

To add an arbiter to an existing replica set:

  • Typically, if there are two or fewer data-bearing members in the replica set, you might need to first set the cluster wide write concern for the replica set.

  • See cluster wide write concern for more information on why you might need to set the cluster wide write concern.

You do not need to change the cluster wide write concern before starting a new replica set with an arbiter.

Tip

See also: 另请参阅:

Default write concern formula

Write Concern Provenance

Starting in version 4.4, MongoDB tracks write concern provenance, which indicates the source of a particular write concern. You may see provenance shown in the getLastError metrics, write concern error objects, and MongoDB logs.

The following table shows the possible write concern provenance values and their significance:

ProvenanceDescription描述
clientSuppliedThe write concern was specified in the application.
customDefaultThe write concern originated from a custom defined default value. See setDefaultRWConcern.
getLastErrorDefaultsThe write concern originated from the replica set's settings.getLastErrorDefaults field.
implicitDefaultThe write concern originated from the server in absence of all other write concern specifications.

Write Concern Contrasted with Commit Quorum

There are important differences between commit quorums and write concerns:

  • Index builds use commit quorums.

  • Write operations use write concerns.

Each data-bearing node in a cluster is a voting member.

The commit quorum specifies how many data-bearing voting members, or which voting members, including the primary, must be prepared to commit a simultaneous index build. before the primary will execute the commit.

The write concern is the level of acknowledgement that the write has propagated to the specified number of instances.

The commit quorum specifies how many nodes must be ready to finish the index build before the primary commits the index build. In contrast, when the primary has committed the index build, the write concern specifies how many nodes must finish the index build before the command returns.