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


Dump=/usr/local/mongodb/bin/mongodump #mongodump命令路Path



Date= ' Date +%y_%m_%d ' #获取当前系统时间

Db_user=myadmin #数据库账号

db_pass=****** #数据库密码


tar_bak= "mongodb_bak_$date.tar.gz"

CD $OUT _dir

RM-RF $OUT _dir/*

Mkdir-p $OUT _dir/$DATE

$DUMP-H $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天前的备份文件


Execute permissions for scripts

[Email protected] mongodb_bak]# chmod +x

Third, testing

Run the script

[email protected] mongodb_bak]# sh +x

View in Directory

To restore data:

[Email protected] mongodb_bak]# mongorestore-h 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/每天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: 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.