Write concern tells MongoDB how sure you want to be that your data is saved safely.
Write concern basics in MongoDB
db.collection.insertOne(document, { writeConcern: { w: <level>, wtimeout: <ms>, j: <boolean> } })w sets how many servers must confirm the write (number or 'majority').
wtimeout sets how long to wait for confirmation before error (in milliseconds).
j specifies whether to wait for the write to be committed to the journal.
db.users.insertOne({name: 'Alice'}, { writeConcern: { w: 1 } })db.orders.insertOne({item: 'Book'}, { writeConcern: { w: 'majority', wtimeout: 5000 } })db.logs.insertOne({event: 'login'}, { writeConcern: { w: 0 } })This command inserts a product and waits for most servers to confirm the write within 3 seconds and ensures the write is saved to the journal (disk).
db.products.insertOne(
{ name: 'Pen', price: 1.5 },
{ writeConcern: { w: 'majority', wtimeout: 3000, j: true } }
)Using w: 'majority' helps protect your data by waiting for most servers to save it.
Setting j: true makes sure the data is written to disk, not just memory.
Higher write concern means safer writes but slower performance.
Write concern controls how sure MongoDB is that your data is saved.
You can choose to wait for one server, many servers, or no confirmation.
Balancing write concern helps keep your app fast and your data safe.