Automatic backup of MongoDB database with shell script

Source: Internet
Author: User
Tags mongodb


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.