0
0
MongoDBquery~5 mins

Write concern levels (w: 1, majority) in MongoDB

Choose your learning style9 modes available
Introduction

Write concern levels tell MongoDB how sure you want to be that your data is saved safely.

When you want to make sure a single server saved your data before moving on.
When you want confirmation that most servers in a group saved your data.
When you want to avoid losing data if a server crashes.
When you want faster writes and can accept some risk of data loss.
When you want the safest write possible for important data.
Syntax
MongoDB
db.collection.insertOne(document, { writeConcern: { w: <level> } })

w can be a number or the word majority.

w: 1 means wait for one server to confirm the write.

w: majority means wait for most servers to confirm.

Examples
Wait for one server to confirm the write.
MongoDB
db.users.insertOne({name: "Alice"}, { writeConcern: { w: 1 } })
Wait for most servers in the replica set to confirm the write.
MongoDB
db.orders.insertOne({item: "Book"}, { writeConcern: { w: "majority" } })
Sample Program

This example inserts two products into the products collection.

The first insert waits for one server to confirm.

The second insert waits for most servers to confirm.

MongoDB
use testdb

// Insert a document with w:1 write concern
 db.products.insertOne({name: "Pen", price: 1.5}, { writeConcern: { w: 1 } })

// Insert a document with majority write concern
 db.products.insertOne({name: "Notebook", price: 3.0}, { writeConcern: { w: "majority" } })
OutputSuccess
Important Notes

Using w: majority is safer but can be slower.

If you use w: 0, MongoDB does not confirm the write at all.

Write concern helps balance speed and safety of your data.

Summary

Write concern controls how many servers confirm a write.

w: 1 waits for one server, w: majority waits for most servers.

Choose write concern based on how safe or fast you want your writes.