write concern描述mongodb对单示例,副本集或分片集写入操作的确认请求级别。在分片集mongos实例会传递write concern到其它实例。
note:
对于多文档事务,在事务级别设置write concern,不要在单独的操作级别,不要对一个事务的单独的写操作设置write concern。
write concern 规范
包括以下字段:
{ w: <value>, j: <boolean>, wtimeout: <number> }
- w:指定写操作传播到的成员数量
比如:
w=1(默认):则要求得到写操作已经传播到独立的Mongod实例或副本集的primary成员的确认
w=0:则不要求确认写操作,可能会返回socket exceptions和 networking errors
w="majority":要求得到写操作已经传播到大多数具有存储数据具有投票的(data-bearing voting )成员(也就是 members[n].votes
值大于0的成员)的确认
- j:要求得到Mongodb的写操作已经写到硬盘日志的确认
比如:
j=true:要求得到Mongodb(w指定的实例个数)的写操作已经写到硬盘日志的确认。j=true本身并不保证因为副本集故障而不会回滚。
- wtimeout:指定write concern的时间限制,只适用于w>1的情况
wtimeout在超过指定时间后写操作会返回error,即使写操作最后执行成功,当这些写操作返回时,MongoDB不会撤消在wtimeout时间限制之前执行成功的数据修改。
如果未指定wtimeout选项且未指定write concern级别,则写入操作将无限期阻止。 指定wtimeout值为0等同于没有wtimeout选项。
Acknowledgment Behavior
Standalone:
j is unspecified | j:true | j:false | |
---|---|---|---|
w: 1 | In memory | On-disk journal | In memory |
w: "majority" | On-disk journal if running with journaling | On-disk journal | In memory |
Replica Sets
w: "majority"
Any data-bearing voting member of the replica set can contribute to write acknowledgment of "majority"
write operations.
j is unspecified | Acknowledgment depends on the value of
|
---|---|
j: true | Acknowledgment requires writing operation to on-disk journal. |
j: false | Acknowledgment requires writing operation in memory. |
w: <number>
Any data-bearing member of the replica set can contribute to write acknowledgment of w: <number> write operations.
The following table lists when the member can acknowledge the write based on the j value:
j is unspecified | Acknowledgment requires writing operation in memory (j:false ). |
---|---|
j: true | Acknowledgment requires writing operation to on-disk journal. |
j: false | Acknowledgment requires writing operation in memory. |