0
0
MongoDBquery~5 mins

Write concern and data durability in MongoDB

Choose your learning style9 modes available
Introduction

Write concern tells MongoDB how sure you want to be that your data is saved safely. It helps protect your data from being lost.

When you want to make sure data is saved on multiple servers before continuing.
When you need to confirm that data is written to disk to avoid losing it if the server crashes.
When you want faster writes and can accept some risk of data loss.
When you want to balance speed and safety depending on your app's needs.
Syntax
MongoDB
db.collection.insertOne(document, { writeConcern: { w: <level>, j: <boolean>, wtimeout: <ms> } })

w sets how many servers must confirm the write (e.g., 1, majority, or 0).

j means waiting for the write to be saved to the journal (disk).

Examples
Waits for confirmation from the primary server only.
MongoDB
db.users.insertOne({name: 'Alice'}, { writeConcern: { w: 1 } })
Waits for most servers to confirm and ensures data is saved to disk journal.
MongoDB
db.orders.insertOne({item: 'Book'}, { writeConcern: { w: 'majority', j: true } })
Does not wait for any confirmation, fastest but no guarantee data is saved.
MongoDB
db.logs.insertOne({event: 'login'}, { writeConcern: { w: 0 } })
Sample Program

This command inserts a document into the inventory collection. It waits for the majority of servers to confirm the write, ensures the write is saved to the journal (disk), and times out if it takes more than 5 seconds.

MongoDB
db.inventory.insertOne(
  { item: 'pen', qty: 50 },
  { writeConcern: { w: 'majority', j: true, wtimeout: 5000 } }
)
OutputSuccess
Important Notes

Using w: 'majority' helps keep data safe by waiting for most servers to confirm.

Setting j: true ensures data is written to disk journal, improving durability.

Higher write concern can slow down writes but protects data better.

Summary

Write concern controls how MongoDB confirms data is saved.

It balances speed and safety for your data.

Use write concern options to match your app's needs for durability.