mongodb使用備份後的oplog做時間點恢復

slnngk發表於2024-04-28

環境:
OS:Centos 7
DB:mongodb 5.0

1.資料庫備份
/opt/mongodb-database-tools/bin/mongodump -h 192.168.56.101:29001 -u test -p test123 --authenticationDatabase admin --db=db_pushmsg -o /tmp/bak

記錄下備份的完成時間:
2024-04-28T14:39:24.628+0800 done dumping db_pushmsg.user (847999 documents)
2024-04-28T14:39:24轉換成UTC時間:1714286364
該時間點用於匯出oplog的開始時間點

2.模擬刪除表
myrepl:PRIMARY> db.user.drop();


3.匯出備份完成時候之後的oplog
mkdir /tmp/oplog
/opt/mongodb-database-tools/bin/mongodump -h 192.168.56.101:29001 -u test -p test123 --authenticationDatabase admin --db=local -c oplog.rs --query '{"ts":{"$gt": {"$timestamp":{"t":1714286364, "i":1}}}}' -o /tmp/oplog

解析:
/opt/mongodb-database-tools/bin/bsondump /tmp/oplog/local/oplog.rs.bson>/tmp/oplog.txt

找到刪除表的時間點
[root@dsc1 tmp]# cat /tmp/oplog.txt|grep drop
{"op":"c","ns":"db_pushmsg.$cmd","ui":{"$binary":{"base64":"rco6crFcRn+aE24ikQd51w==","subType":"04"}},"o":{"drop":"user"},"o2":{"numRecords":{"$numberInt":"1000000"}},"ts":{"$timestamp":{"t":1714286707,"i":1}},"t":{"$numberLong":"3"},"v":{"$numberLong":"2"},"wall":{"$date":{"$numberLong":"1714286707948"}}}

刪除的時間點為:1714286707

4.備份檔案和oplog備份複製到異機
[root@dsc1 tmp]# scp -r bak root@192.168.56.103:/tmp/
[root@dsc1 tmp]# scp -r oplog root@192.168.56.103:/tmp/

5.異機恢復資料庫
/opt/mongodb-database-tools/bin/mongorestore -h 192.168.56.103:27001 -u test -p test123 --authenticationDatabase admin -d db_pushmsg /tmp/bak/db_pushmsg

6.日誌應用
/opt/mongodb-database-tools/bin/mongorestore -h 192.168.56.103:27001 -u test -p test123 --authenticationDatabase admin --oplogReplay --oplogLimit "1714286707:1" /tmp/oplog/local/oplog.rs.bson

相關文章