Problem Statement
Explain write concerns in MongoDB. What is the difference between w:1, w:'majority', and w:'all'?
Explanation
Write concern in MongoDB defines the level of acknowledgment requested from MongoDB for write operations. It determines how many replica set members must acknowledge a write before the operation returns success. This balances durability against performance.
Write concern w 1 is the default, requiring acknowledgment only from the primary node. The write is considered successful once the primary has written the data, even before it replicates to secondaries. This is fast but provides the least durability. If the primary fails immediately after acknowledging but before replication, the write could be lost.
Write concern w majority requires acknowledgment from the majority of replica set members, including the primary. For a three-member replica set, this means at least two nodes must acknowledge the write. This provides strong durability because the data exists on multiple nodes before success is returned. If the primary fails, the data is safe because it has been replicated to at least one secondary.
Write concern w all requires acknowledgment from all replica set members. This provides maximum durability but is rarely used because it is slow and makes the system sensitive to any member being unavailable. If any member is down, writes with w all will fail or timeout.
You can also specify wtimeout to limit how long to wait for the requested write concern. If the timeout is reached before enough members acknowledge, the write may still succeed on the primary, but the operation returns an error.
Code Solution
SolutionRead Only
// w:1 - primary only (default, fastest)
db.orders.insertOne(
{ item: "book", qty: 1 },
{ writeConcern: { w: 1 } }
)
// w:'majority' - majority of members (durable)
db.orders.insertOne(
{ item: "book", qty: 1 },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
// w:'all' - all members (slowest, most durable)
db.orders.insertOne(
{ item: "book", qty: 1 },
{ writeConcern: { w: "all", wtimeout: 5000 } }
)