First, create a MongoDB backup directory
Used to store data
mkdir
-p
/data/mongodb_bak/mongodb_bak_now
mkdir
-p
/data/mongodb_bak/mongodb_bak_list
Ii. Creating a MongoDB database backup script
#!/bin/bash
#
Dump=/usr/local/mongodb/bin/mongodump #mongodump命令路Path
Out_dir=/data/mongodb_bak/mongodb_bak_now #临时备份目录
Tar_dir=/data/mongodb_bak/mongodb_bak_list #备份存放路径
Date= ' Date +%y_%m_%d ' #获取当前系统时间
Db_user=myadmin #数据库账号
db_pass=****** #数据库密码
DAYS=20
#DAYS=20代表删除20天前的备份,即只保留近20天的备份
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 #压缩为. tar.gz format
Find $TAR _dir/-mtime + $DAYS-delete #删除20天前的备份文件
Exit
Execute permissions for scripts
[Email protected] mongodb_bak]# chmod +x mongodb_bak.sh
Third, testing
Run the script
[email protected] mongodb_bak]# sh +x mongodb_bak.sh
View in Directory
To restore data:
[Email protected] mongodb_bak]# mongorestore-h 127.0.0.1:27017-d cara2/data/mongodb_bak/mongodb_bak_now/2018_07_25 /cara
Enter the database to view:
The data is OK, it means the backup is okay!
Iv. Adding timed tasks
[Email protected] ~]# CRONTAB-E
* * * * */data/mongodb_bak/mongodb_bak.sh#每天18:00执行MongoDB数据库备份脚本
Automatic backup of MongoDB database with shell script