目录
一、mongodump
使用 mongodump 进行逻辑备份,可实现全量备份与增量备份,可同时备份数据库的索引。导出的数据为 bson 格式,可以使用 bsondump 转换为 json 格式。
逻辑备份性能很低,稳定性不高,有条件推荐物理备份。
1、全量备份
(1). 导出数据库 db1 中的集合 t1 至同目录下的dump文件夹下
mongodump --host 10.10.50.210 -u test -p testpw --authenticationDatabase admin -d db1 -c t1
(2). 导出至同目录下自定义的文件夹
mongodump --host 10.10.50.210 -u test -p testpw --authenticationDatabase admin -d db1 -c t1 -o selfdir
2、增量备份
导出 local.oplog.rs 中的oplog数据,可以配合 query 进行数据过滤,比如 时间戳、操作或数据空间的过滤。
mongodump --host 10.10.50.210 -u test -p testpw --authenticationDatabase admin -d local -c oplog.rs --query '{ts:{$gte:Timestamp(1660014692, 1)}, op:{$ne:"n"}}'
3、自定义mongodump
mongodump在 github 上有源码,使用go语言编写的,可以根据需求进行二次开发。
二、mongorestore
与 mongodump 配合使用,可以恢复全量备份的bson数据,也可重放 oplog 数据。
1、全量数据恢复
mongorestore --host 10.10.50.210 -u test -p testpw --authenticationDatabase admin ./13-34/db1/t1.bson
2、增量数据恢复
对于oplog的bson文件,名称必须是固定的(oplog.rs.bson),可自定义最外层的目录名称(如以当前日期)。
注意 oplog 数据的恢复不是简单的将数据还原到 local.oplog.rs 中,而是进行数据的重放。
mongorestore --host 10.10.50.210 -u test -p testpw --authenticationDatabase admin --oplogReplay ./13-36/local/oplog.rs.bson