Linux MongoDB database automatic backup details

  • 2020-06-23 02:12:58
  • OfStack

This article is mainly about Linux MongoDB database automatic backup related content, Shared for your reference and learning, the following is a detailed introduction:

1. Create MongoDB backup directory


mkdir -p /data/mongodb_bak/mongodb_bak_now
mkdir -p /data/mongodb_bak/mongodb_bak_list

2. New MongoDB database backup script (/data/mongodb_bak/ ES14en_bak.sh)


#!/bin/bash 
#backup MongoDB 
 
#mongodump The command path  
DUMP=/usr/local/mongodb/bin/mongodump 
# Temporary backup directory  
OUT_DIR=/data/mongodb_bak/mongodb_bak_now 
# Backup storage path  
TAR_DIR=/data/mongodb_bak/mongodb_bak_list 
# Gets the current system time  
DATE=`date +%Y_%m_%d` 
# Database account  
DB_USER=user 
# Database password  
DB_PASS=123 
#DAYS=15 On behalf of the delete 15 Days before the backup, that is, only keep close 15 Days of backup  
DAYS=15 
# The final saved database backup file  
TAR_BAK="mongodb_bak_$DATE.tar.gz" 
 
cd $OUT_DIR 
rm -rf $OUT_DIR/* 
mkdir -p $OUT_DIR/$DATE 
# Back up all databases  
$DUMP -h 15.62.32.112:27017 -u $DB_USER -p $DB_PASS --authenticationDatabase "admin" -o $OUT_DIR/$DATE 
# Compressed into .tar.gz format  
tar -zcvf $TAR_DIR/$TAR_BAK $OUT_DIR/$DATE 
# delete 15 Days before the backup file  
find $TAR_DIR/ -mtime +$DAYS -delete 
 
exit 

3. Modify file properties to make them executable


chmod +x MongoDB_bak.sh

4. Modify /etc/crontab to add scheduled tasks


vi /etc/crontab
# Every week 6 evening 20:30 Start to perform MongoDB Database backup script 
30 20 * * 6 root /data/mongodb_bak/MongoDB_bak.sh 

Appendix: MongoDB database recovery


# Restore all databases 
mongorestore -u $DB_USER -p $DB_PASS --authenticationDatabase "admin" --noIndexRestore --dir /data/mongodb_bak/mongodb_bak_now/2016_12_17/
# Restoring a single database 
mongorestore -u $DB_USER -p $DB_PASS --authenticationDatabase "admin" --noIndexRestore -d dbname --dir /data/mongodb_bak/mongodb_bak_now/2016_12_17/dbname

Partial parameter description

--drop parameter: Delete the original data before restoring it to avoid data duplication --noIndexRestore parameter: No index is created when data is restored --dir parameter: database backup directory -d parameter: followed by the name of the database to be restored

conclusion


Related articles: