Problem Statement
What does write concern { w: 'majority' } ensure?
Explanation
Write concern w majority ensures that write operations are acknowledged by the majority of replica set members before returning success. This provides strong durability guarantees, as data is replicated to multiple nodes.
Using majority write concern prevents data loss during failover because the majority of nodes have the data. However, it adds latency compared to default write concern because the operation waits for replication. Other write concern options include w 1 for primary acknowledgment only, and w all for all members.
Code Solution
SolutionRead Only
// Write with majority concern
db.users.insertOne(
{ name: "Alice" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
// Set default write concern for database
db.adminCommand({
setDefaultRWConcern: 1,
defaultWriteConcern: { w: "majority" }
})