Navigation
This version will reach end of life on Feb 2018. To upgrade, go to the Learn more about upgrading your version of MongoDB.

Write Concern for Replica Sets

From the perspective of a client application, whether a MongoDB instance is running as a single server (i.e. “standalone”) or a replica set is transparent. However, replica sets offer some configuration options for write operations. [1]

[1]Sharded clusters where the shards are also replica sets provide the same configuration options with regards to write and read operations.

Verify Write Operations to Replica Sets

For a replica set, the default write concern requests acknowledgement only from the primary. You can, however, override this default write concern, such as to confirm write operations on a specified number of the replica set members.

Write operation to a replica set with write concern level of ``w:2`` or write to the primary and at least one secondary.

To override the default write concern, specify a write concern with each write operation. For example, the following method includes a write concern that specifies that the method return only after the write propagates to the primary and at least one secondary or the method times out after 5 seconds.

db.products.insert(
   { item: "envelopes", qty : 100, type: "Clasp" },
   { writeConcern: { w: 2, wtimeout: 5000 } }
)

You can include a timeout threshold for a write concern. This prevents write operations from blocking indefinitely if the write concern is unachievable. For example, if the write concern requires acknowledgement from 4 members of the replica set and the replica set has only available 3 members, the operation blocks until those members become available. See wtimeout.

Modify Default Write Concern

You can modify the default write concern for a replica set by setting the getLastErrorDefaults setting in the replica set configuration. The following sequence of commands creates a configuration that waits for the write operation to complete on a majority of the voting members before returning:

cfg = rs.conf()
cfg.settings = {}
cfg.settings.getLastErrorDefaults = { w: "majority", wtimeout: 5000 }
rs.reconfig(cfg)

If you issue a write operation with a specific write concern, the write operation uses its own write concern instead of the default.

Custom Write Concerns

You can tag the members of replica sets and use the resulting tag sets to create custom write concerns. See Configure Replica Set Tag Sets for information on configuring custom write concerns using tag sets.