🍃 MongoDB Intermediate

What is MongoDB's write concern?

Answer

Write concern specifies the level of acknowledgment requested from MongoDB for write operations — it controls the trade-off between write speed and data durability. Write concern options: w (required acknowledgment): 0 — fire and forget, no acknowledgment (fastest, data loss possible); 1 — primary acknowledges (default — primary has written to memory); "majority" — majority of replica set members have acknowledged (most durable — survives primary failure); N — N members must acknowledge. j (journal): false (default) — acknowledged when in memory; true — acknowledged only after written to the on-disk journal (WAL) — survives process crash. wtimeout: timeout in milliseconds for the write concern — throws WriteConcernError if not acknowledged within this time. Common configurations: w:1, j:false — default, in-memory acknowledgment — fast but minor data loss window (MongoDB crash before journal flush); w:1, j:true — on-disk durability on primary — survives crashes; w:"majority", j:true — strongest guarantee — survives primary failure with on-disk durability. Setting at operation level: db.orders.insertOne({ ... }, { writeConcern: { w: "majority", j: true, wtimeout: 5000 } }). Setting at connection level: in the connection string: mongodb://host/?w=majority&j=true. For financial or critical data, always use w:"majority", j:true.