Step Into Write Concern of MongoDB

Write concern is a balance between response time(performance) and the success of a write operation(Reliability).
Write includes insert, udpate and delete.
A weak write concern: write operations return quickly, but data maybe not persist well(including replica set).
A strong write concern: clients wait after mongodb confirm the write operation suncessful.

Levels

listed from weakest to strongest

  • Unacknowledged {W:0}

    similar to errors ignored

  • Acknowledged {W:1}
    used in writing unimportant data, e.g. some operation log, user’s behavior(click, time staying in one page)

    default write concern
    the mongod confirms that it received the write operation and applied the change to the in-memory view of data
    allows clients to catch network, duplicate key, and other errors
    does not confirm that the write operation has persisted to the disk system

  • Journaled {w:1,j:true}
    used in writing key, business data, e.g. order, account

    committing the data to the journal(journaling enabled first)
    ensures that MongoDB can recover the data following a shutdown or power interruption

  • Replica Acknowledged {w:2}

    guarantee write sucessfully to one Replica Set beside the primary

Timeouts

  • set at client side
  • wtimeout: in milliseconds
  • wtimeout causes write operations to return with an error after the specified limit, even if the required write concern will eventually succeed
  • MongoDB does not “rollback” or undo modifications made before the wtimeout interval expired

getLastError()

Driver implicitly and immediately call this method after one write operation
depending on level of Write Corcern

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//after insert(), implicitly call db.getLastError(); if capturing error, assign it to err of callback function.
// when w:-1, err is always null
// when w:0, except network error, normally no other error can be captured
// when w:1, return error from mongod to err parameter
db.collection("test", {}, function(err, collection) {
collection.insert({
name: "world peace"
},
function(err, result) {
assert.equal(null, err);
console.log(result);
db.close();
})
});