How it works
The explanation, with examples you can run.
What the defaults are
db.adminCommand({ getDefaultRWConcern: 1 }){ "defaultReadConcern": { "level": "local" }, "defaultWriteConcern": { "w": "majority", "wtimeout": 0 }, "defaultWriteConcernSource": "implicit", "defaultReadConcernSource": "implicit" }Since MongoDB 5.0 the implicit default write concern is w: "majority", with one exception: in a replica set with arbiters where the data-bearing members are not more than a majority of voters (the classic primary-secondary-arbiter), it is w: 1. Many older drivers and code samples also set w: 1 explicitly.
Write concern
| Setting | Acknowledged when | Can it roll back? |
|---|---|---|
w: 0 | Never; fire and forget | Yes, and you will not know if it failed |
w: 1 | The primary has applied it | Yes, if the primary fails before a secondary copies it |
w: "majority" | A majority of data-bearing voting members have it in their oplog (journaled by default) | No |
j: true | Also written to the on-disk journal | j: true alone does not prevent rollback |
wtimeout limits how long to wait for the acknowledgement. It does not cancel anything. With one of three members stopped:
db.payments.insertOne({ _id: 2, amount: 700 }, { writeConcern: { w: 3, wtimeout: 2000 } })MongoWriteConcernError: waiting for replication timed out{ code: 64, codeName: 'WriteConcernTimeout', errInfo: { wtimeout: true, ... } }db.payments.countDocuments({ _id: 2 }) // 1The insert failed from the client's point of view but the document exists. After a write concern error or a network error the outcome is unknown, which is why retries should be idempotent (an upsert keyed on a business id, not a blind insert).
Read concern
local(default): the member's latest data, which may include writes that are later rolled back.available: likelocal; on sharded clusters it can also return orphaned documents. Fastest, weakest.majority: only data acknowledged by a majority, so it never rolls back. It may be slightly behind the newest writes.linearizable: majority data that reflects every majority write completed before the read began; primary only, slower.snapshot: a consistent point-in-time view, used by transactions.
Read preference
primary (default), primaryPreferred, secondary, secondaryPreferred and nearest. Reading from secondaries spreads load and keeps reads working during an election, but replication is asynchronous, so a secondary can be seconds behind under load. maxStalenessSeconds excludes secondaries that are too far behind. For read-your-writes across members, use a causally consistent session with majority read and write concern; otherwise read from the primary.
Check yourself
3 questions. Get them all right to finish this topic.
0 of 3 right so far. Get all three to finish this topic.