Mongodb自动备份及恢复
安装
1 2 3 4 5 6
| curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz tar -zxvf mongodb-linux-x86_64-3.0.6.tgz
mv mongodb-linux-x86_64-3.0.6/ /usr/local/mongodb
mkdir -p /usr/local/mongodb/data
|
运行
1
| nohup /usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data &
|
手动备份和恢复
备份:
1
| mongorestore -u $DB_USER -p $DB_PASS --authenticationDatabase "admin" --noIndexRestore --dir /data/mongodb_bak/mongodb_bak_now/2016_12_17/
|
恢复备份:
1
| /usr/local/mongodb/bin/mongorestore --noIndexRestore --dir /data/mongodb_bak/mongodb_bak_now/2018_12_29/
|
Linux下MongoDB自动备份
创建MongoDB备份目录
1 2
| mkdir -p /data/mongodb_bak/mongodb_bak_now mkdir -p /data/mongodb_bak/mongodb_bak_list
|
新建MongoDB数据库备份脚本
/data/mongodb_bak/MongoDB_bak.sh
chmod +x MongoDB_bak.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #!/bin/bash
DUMP=/usr/local/mongodb/bin/mongodump
OUT_DIR=/data/mongodb_bak/mongodb_bak_now
TAR_DIR=/data/mongodb_bak/mongodb_bak_list
DATE=`date +%Y_%m_%d`
DB_USER=user
DB_PASS=123
DAYS=15
TAR_BAK="mongodb_bak_$DATE.tar.gz"
cd $OUT_DIR rm -rf $OUT_DIR/* mkdir -p $OUT_DIR/$DATE
$DUMP -h 127.0.0.1:27017 -u $DB_USER -p $DB_PASS --authenticationDatabase "admin" -o $OUT_DIR/$DATE
tar -zcvf $TAR_DIR/$TAR_BAK $OUT_DIR/$DATE
find $TAR_DIR/ -mtime +$DAYS -delete
exit
|
修改/etc/crontab,添加计划任务
vi /etc/crontab
1 2
| 30 20 * * 6 root /data/mongodb_bak/MongoDB_bak.sh
|
附录:MongoDB数据库恢复
1 2 3 4
| /usr/local/mongodb/bin/mongodump --authenticationDatabase "admin" -o /data/mongodb_bak/mongodb_bak_now/
/usr/local/mongodb/bin/mongorestore --authenticationDatabase "admin" --noIndexRestore --dir /data/mongodb_bak/mongodb_bak_now/
|
1 2 3 4
| mongorestore -u $DB_USER -p $DB_PASS --authenticationDatabase "admin" --noIndexRestore --dir /data/mongodb_bak/mongodb_bak_now/2016_12_17/
mongorestore -u $DB_USER -p $DB_PASS --authenticationDatabase "admin" --noIndexRestore -d dbname --dir /data/mongodb_bak/mongodb_bak_now/2016_12_17/dbname
|
部分参数说明
- drop参数:恢复数据之前删除原来的数据,避免数据重复
- noIndexRestore参数:恢复数据时不创建索引
- dir参数:数据库备份目录
- d参数:后面跟要恢复的数据库名称