Write operations in MongoDB need to be handled carefully to ensure data durability, consistency, and performance. MongoDB provides write concern options to control how write operations are acknowledged.
Write Concern in MongoDB
Write concern determines how MongoDB confirms a write operation before returning success.
Types of Write Concern:
Write Concern Description
{ w: 0 } No acknowledgment (fire-and-forget).
{ w: 1 } Acknowledgment from the primary node (default).
{ w: "majority" } Acknowledgment from most nodes in a replica set.
{ j: true } Acknowledgment only after data is written to the journal.
{ w: 2, j: true } Acknowledgment after data is written to two nodes and journaled.
Handling Write Concerns in Queries
You can specify write concern at the operation level.
Example 1: Basic Write with Default Acknowledgment (w: 1)
db.orders.insertOne(
{ item: "Laptop", price: 50000 },
{ writeConcern: { w: 1 } }
)
Example 2: Stronger Write Concern (w: "majority", j: true)
db.orders.insertOne(
{ item: "Phone", price: 25000 },
{ writeConcern: { w: "majority", j: true } }
)
Example 3: Faster Writes with No Acknowledgment (w: 0)
db.orders.insertOne(
{ item: "Tablet", price: 15000 },
{ writeConcern: { w: 0 } }
)
Handling Write Failures
Write operations can fail due to network issues, replication lag, or primary node failure. Use try-catch blocks in application code to handle failures.
Example: Handling Write Errors in JavaScript
try {
db.orders.insertOne(
{ item: "Headphones", price: 2000 },
{ writeConcern: { w: "majority", j: true } }
);
print("Write successful");
} catch (e) {
print("Write failed:", e);
}