Durability
定义:只要commit成功(或者说server 返回acknowledge),操作就会被持久化到硬盘上。
实现方式:采用write-ahead log(WAL),即 journal。在数据真正写入数据库之前,先写入journal文件中。同时也提供了数据的原子性。
Journal
Mongodb中journal的格式与oplog一致,大小约为100MB一个文件。
WT engine内存中也有一份journal,每50ms或者journal达到100MB,WT把内存中的journal 写入硬盘。最小Journal为128bytes。每60秒,会创建一个snapshot
Mmapv1 engine 每100ms将private-view中变动的数据写入journal,并remap shared view。每60秒(checkpoint)将shared view的数据写入数据库中。即journal提供的是每个checkpoint间的durability。
没有开启journal的话,数据是每60秒从内存写入硬盘。
写入journal的数据会被压缩,使用的压缩算法是snappy。
writeConcern 的 j 选项
写操作仅在writeconcern要求的成员数量都写入自己的jorunal之后,才会返回成功。
db.products.insertOne(
{ sku: “H1100335456”, item: “Electric Toothbrush Head”, quantity: 3 },
{ writeConcern: { w : “majority”, wtimeout : 100, j : true }
}
Durability of Transactions
为了保证事务的原子性。Write concern 0 is not supported for transactions.
mongodb 4.0开始支持涉及多个文档的事务的原子性和持久性
function updateEmployeeInfo(session) {
employeesCollection = session.getDatabase(“hr”).employees; eventsCollection = session.getDatabase(“reporting”).events; session.startTransaction( {writeConcern: { w: “majority” } } ); try{
employeesCollection.updateOne( { employee: 3 }, { $set: { status: “Inactive” } } );
eventsCollection.insertOne( { employee: 3, status: { new: “Inactive”, old: “Active” } } );
} catch (error) {
print(“Caught exception during transaction, aborting.”); session.abortTransaction();
throw error;
}
commitWithRetry(session);}