通过重放 oplog 进行时间点还原(回到错误 drop/delete 之前)
MongoDB备份命令
# 1) Full backup + oplog written during the backup (whole instance, from a replica set member):
mongodump --uri="mongodb://admin@mongo2:27017/?authSource=admin&readPreference=secondary" --oplog --gzip --out=/backup/full
# 2) Find the time of the bad operation (mongosh): db.getSiblingDB("local").oplog.rs.find({ "o.drop": "musteri" }).sort({ $natural: -1 }).limit(1)
# 3) Dump the oplog after the backup (t: start time of the full backup, epoch seconds):
mongodump --uri="mongodb://admin@mongo2:27017/?authSource=admin" --db=local --collection=oplog.rs --query='{"ts":{"$gte":{"$timestamp":{"t":1791400000,"i":1}}}}' --out=/backup/oplog
# 4) Restore the full backup together with its own oplog:
mongorestore --uri="mongodb://admin@target:27017/?authSource=admin" --gzip --oplogReplay /backup/full
# 5) Replay the oplog up to the bad operation (oplogLimit is exclusive):
mkdir /backup/pitr && mv /backup/oplog/local/oplog.rs.bson /backup/pitr/oplog.bson
mongorestore --uri="mongodb://admin@target:27017/?authSource=admin" --oplogReplay --oplogLimit=1791403600:1 /backup/pitr作用
用 --oplog 使完整备份保持一致,然后重放备份后累积的 oplog,直到错误操作(drop、批量删除)的时间戳,将数据恢复到该时刻。
适用场景
集合被误删,或执行了错误的批量更新/删除,需要恢复到损坏前的最后状态时。
注意
还原到单独的目标,而不是生产系统,验证后再迁移所需数据。从备份开始到错误操作之间的 oplog 必须仍在 oplog 窗口内;已滑出窗口的操作无法恢复。--oplog 仅适用于完整实例转储(不能与 --db 同时使用)。在分片集群上无法用 mongodump 实现一致的 PITR;需要文件系统快照或备份产品。