0
0
MongoDBquery~5 mins

Write concern levels (w: 1, majority) in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Write concern levels (w: 1, majority)
O(w)
Understanding Time Complexity

When we write data to MongoDB, the database confirms the write in different ways.

We want to understand how the time to confirm a write changes with different write concern levels.

Scenario Under Consideration

Analyze the time complexity of these write operations with different write concerns.


// Write with w:1 (acknowledge from primary only)
db.collection.insertOne({name: "Alice"}, {writeConcern: {w: 1}})

// Write with w: "majority" (acknowledge from majority of nodes)
db.collection.insertOne({name: "Bob"}, {writeConcern: {w: "majority"}})
    

This code writes a document and waits for confirmation from either the primary node or the majority of nodes.

Identify Repeating Operations

Look at what happens behind the scenes when confirming writes.

  • Primary operation: Waiting for acknowledgments from nodes.
  • How many times: For w:1, once from primary; for w: "majority", from multiple nodes.
How Execution Grows With Input

The time to confirm a write depends on how many nodes must respond.

Input Size (n)Approx. Operations
3 nodesw:1 waits for 1 response; w:majority waits for 2 responses
5 nodesw:1 waits for 1 response; w:majority waits for 3 responses
7 nodesw:1 waits for 1 response; w:majority waits for 4 responses

Pattern observation: w:1 time stays the same; w:majority time grows roughly with half the number of nodes.

Final Time Complexity

Time Complexity: O(w)

This means the time to confirm a write grows with the number of nodes that must acknowledge it.

Common Mistake

[X] Wrong: "Waiting for majority is always the same speed as waiting for one node."

[OK] Correct: Majority requires more nodes to respond, so it usually takes longer than just one node.

Interview Connect

Understanding how write concern affects response time helps you explain trade-offs between speed and data safety in real systems.

Self-Check

"What if we changed write concern to w: 0 (no acknowledgment)? How would the time complexity change?"