0
0
MongoDBquery~5 mins

Write concern basics 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.

When you want to make sure your data is saved on the main server before moving on.
When you want to wait until data is copied to backup servers for extra safety.
When you want to speed up writing data and don't need to wait for confirmation.
When you want to avoid losing data during a power failure or crash.
When you want to balance between speed and safety for your app's data.
Syntax
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.

Examples
Waits for the primary server to confirm the write.
MongoDB
db.users.insertOne({name: 'Alice'}, { writeConcern: { w: 1 } })
Waits for most servers to confirm within 5 seconds.
MongoDB
db.orders.insertOne({item: 'Book'}, { writeConcern: { w: 'majority', wtimeout: 5000 } })
Does not wait for any confirmation, fastest but less safe.
MongoDB
db.logs.insertOne({event: 'login'}, { writeConcern: { w: 0 } })
Sample Program

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).

MongoDB
db.products.insertOne(
  { name: 'Pen', price: 1.5 },
  { writeConcern: { w: 'majority', wtimeout: 3000, j: true } }
)
OutputSuccess
Important Notes

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.

Summary

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.