Some time ago, my personal server database was deleted inexplicably, I learned of the situation in tears.

Later, I searched a lot of information about restoring the database, but basically rely on backup to restore, and as a little white I did not regularly back up my database.

Fortunately, I didn’t have much data in my database, so I decided to start from scratch.

After the pain of the lesson, the first thing I do is to give my server a regular backup script, after all, can not fall twice in the same place.

Write a blog about it in case you need to use it again.

Creating a Backup Directory

#Temporary backup folder
mkdir -p /home/mongodb_bak/mongodb_bak_now
#Backup package folder
mkdir -p /home/mongodb_bak/mongodb_bak_list
Copy the code

Creating a Backup Script

vim /home/crontab/MongoDB_bak.sh
Copy the code
#! /bin/sh
#The dump execution path depends on the mongodb installation path
DUMP=/usr/bin/mongodump
#Temporary backup path
OUT_DIR=/home/backup/mongod_bak/mongod_bak_now
#Directory for storing compressed backup files
TAR_DIR=/home/backup/mongod_bak/mongod_bak_list
#Current system time
DATE=`date +%Y-%m-%d`
#Database account
DB_USER=username
#Database password
DB_PASS=password
#Indicates that the backup generated 7 days ago is deleted. That is, only the backup generated in the latest 7 days is retained
DAYS=7
#The final saved database backup file
TAR_BAK="mongod_bak_$DATE.tar.gz"

cd $OUT_DIR
rm -rf $OUT_DIR/*
mkdir -p $OUT_DIR/$DATE
$The DUMP - h 127.0.0.1:27017 - u$DB_USER -p $DB_PASS --authenticationDatabase admin -o $OUT_DIR/$DATE
#The compressed format is.tar.gz
tar -zcvf $TAR_DIR/$TAR_BAK $OUT_DIR/$DATE
#Delete backup files generated 15 days ago
find $TAR_DIR/ -mtime +$DAYS -delete

exit
Copy the code

Change DB_USER to your database account and DB_PASS to your database password.

Modifying Script Permissions

chmod +x /home/crontab/MongoDB_bak.sh
Copy the code

Adding a Scheduled Task

vi /etc/crontab
Copy the code

Add something:

#Backup every Saturday at 18:30
30 18 * * 6 root /home/crontab/MongoDB_bak.sh
Copy the code

The first number represents minutes, the second hour, the third day, the fourth month, and the fifth week.

# Example of job definition:
# .---------------- minute (0 - 59)
#| .------------- hour (0 - 23)
#| | .---------- day of month (1 - 31)
#| | | .------- month (1 - 12) OR jan,feb,mar,apr ...
#| | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
#| | | | |
# *  *  *  *  * user-name  command to be executed
Copy the code

The script takes effect after being saved.

Database Recovery

#Restore all databasesMongorestore -u < database account > -p < database password > --authenticationDatabase "admin" --noIndexRestore --dir < backup folder path >#Restoring a single databaseMongorestore -u < database account > -p < database password > --authenticationDatabase "admin" --noIndexRestore -d < database name > --dir < backup file path >Copy the code