备份:mongodump
mongodump常用参数
- --db:指定导出的数据库
- --collection:指定导出的集合
- --excludeCollection:指定不导出的集合
- --host :远程ip
- --username:开启身份验证后,用户的登录名
- -- password:用户的密码
- --out(指定输出目录):如果不使用这个参数,mongodump将输出文件保存在当前工作目录中名为dump的目录中
- --archive:导出归档文件,最后只会生成一个文件
- --gzip:压缩归档的数据库文件,文件的后缀名为.gz
注意: --archive 与 --out 不能一起用
单库备份
mongorestore -h 127.0.0.1:27017 -d danny ./danny/
全库备份
mongodump -h 127.0.0.1:27017
归档备份
mongodump -h 127.0.0.1:27017 --archive=./all.archive
压缩归档备份
mongorestore -h 127.0.0.1:27017 --gzip --archive=all.archive
还原:mongorestore
单库还原
mongorestore -h 127.0.0.1:27017 -d danny ./danny/
全库还原
mongorestore -h 127.0.0.1:27017 ./dump/
归档还原
mongorestore -h 127.0.0.1:27017 --archive=./all.archive
压缩归档还原
mongorestore -h 127.0.0.1:27017 --gizp --archive=all.archive
注:生产备份脚本常用压缩归档备份还原
简单脚本示例:
#!/bin/bash targetpath='/data/mongodb_backup' nowtime=$(date +%F-%T) start() { /usr/bin/mongodump --host 127.0.0.1 --port 27017 --gzip --archive=${targetpath}/$nowtime.archive } execute() { start if [ $? -eq 0 ] then echo "back successfully!" else echo "back failure!" fi } execute echo "============== back end ${nowtime} =============="