MongoDB.oplog相关浅析

1. oplog里面有啥

        MongoDB 的Replication是通过一个日志来存储写操作的,这个日志就叫做oplog。
在默认情况下,oplog分配的是5%的空闲磁盘空间。通常而言,这是一种合理的设置。可以通过mongod --oplogSize来改变oplog的日志大小。
oplog是capped collection,因为oplog的特点(不能太多把磁盘填满了,固定大小)需要,MongoDB才发明了capped collection(the oplog is actually the reason capped collections were invented).

2. oplog存在哪里

        一般oplog存储在mongo的local库中(replica sets架构下通过db.oplog.rs访问),local库是MongoDB的系统库,记录着时间戳和索引和复制集等信息,具体包括以下内容:
MongoDB.oplog相关浅析

  • me集合保存了服务器名称
  • replset.minvalid集合保存了数据库最新操作的时间戳
  • startup_log集合记录这mongod每一次的启动信息
  • system.indexes集合记录当前库的所有索引信息
  • system.replset记录着复制集的成员配置信息rs.conf()读取这个集合
  • oplog.rs集合记录着所有操作,MongoDB就是通过oplog.rs来实现数据同步的。当Primary节点插入一条数据后,oplog.rs集合中就会多一条记录。

3. oplog是啥结构的

如下图:
MongoDB.oplog相关浅析

  • ts: the time this operation occurred.8字节的时间戳,由4字节unix timestamp + 4字节自增计数表示
  • h: a unique ID for this operation. Each operation will have a different value in this field.操作ID,每个操作都有不同的ID
  • op: the write operation that should be applied to the slave. n indicates a no-op, this is just an informational message.1字节的操作类型
  • ns: the database and collection affected by this operation. Since this is a no-op, this field is left blank.操作所在的namespace
  • o: the actual document representing the op. Since this is a no-op, this field is pretty useless.
    The o field now contains the document to insert or the criteria to update and remove. Notice that, for the update, there are two o fields (o and o2). o2 give the update criteria and o gives the modifications (equivalent to update()‘s second argument).操作所对应的document,即当前操作的内容(比如更新操作时要更新的的字段和值,插入操作的字段和值)
  • o2:这个字段在执行update操作的时候会出现

op包括以下几种操作类型:
“i”: insert
“u”: update
“d”: delete
“c”: db cmd
“n”: no op,即空操作,其会定期执行以确保时效性 。修改配置,会产生 “n” 操作

4. oplog怎么查

        已经知道了结构,其他的就是mongo基础啦。其中db.getReplicationInfo()可以获取oplog的当前状态:
MongoDB.oplog相关浅析