Intermediate LevelMongoDB & Mongoose
What is MongoDB Write Concern (w: "majority", j: true) and how does it guarantee durability?
❓ Interview Prompt: Explain Write Concern parameters (w: 1, w: "majority", j: true, wtimeout), journaling (on-disk write buffer), and data durability guarantees.
Write Concern specifies the level of acknowledgment requested from MongoDB for write operations:
Key Parameters:
•
'w: 1': Default. Acknowledges write after primary node memory write.
•
'w: "majority"': Acknowledges write ONLY after a majority of replica set nodes apply the write, preventing rollback if primary crashes!
•
'j: true': Requires write to be flushed to the on-disk Journal file before responding.
Code Implementation Example
typescript
import { UserModel } from './models/User';
async function saveCriticalUser() {
const user = new UserModel({ name: 'Bob', email: 'bob@example.com' });
// Request majority acknowledgment and on-disk journal flush
await user.save({
writeConcern: { w: 'majority', j: true, wtimeout: 5000 }
});
}💡Enforcing w:majority and j:true write concern for critical user transactions.
🎯 Interview Key Takeaway
Use w:majority and j:true write concern for financial or critical writes to guarantee data durability across replica crashes.
#Write Concern#w:majority#Journaling#Durability#Intermediate
Back to all MongoDB & Mongoose Questions→