Mongo自动备份

功能说明

  • 每天凌晨3点备份当前状态下的mongo数据,保存的日期为前一天,如:2015年11月12号凌晨保存的数据目录名为20151111。

  • 然后每天都会删除四天之前所备份的数据(意思是仅保留最近三天的备份数据)。

具体实现

  • 执行备份的脚本:backup.bat
#!/bin/bash

#存放备份数据的路径
targetpath='/home/sam/mongodb/'
#获取昨天的日期
nowtime=$(date -d '-1 days' +"%Y%m%d")

#如果昨天的文件不存在
if [ ! -d ${targetpath}/${nowtime}/ ]
then
  #创建昨天的数据文件夹
  mkdir ${targetpath}/${nowtime}
fi

#备份数据到指定文件夹
mongodump -h 127.0.01 -o ${targetpath}/${nowtime}
  • 执行删除的脚本:remove.bat
#!/bin/bash

#存放备份数据的路径
targetpath='/home/sam/mongodb/'
#获取前第四天的日期
nowtime=$(date -d '-4 days' +"%Y%m%d")

#如果该文件夹存在
if [ -d ${targetpath}/${nowtime}/ ]
then
  #删除该文件夹
  rm -rf ${targetpath}/${nowtime}
fi
  • 执行恢复数据的脚本:restore.bat
#!/bin/bash

#存放备份数据的路径
targetpath='/home/sam/mongodb/'
#获取前第一天的日期
time1=$(date -d '-1 days' +"%Y%m%d")
#获取前第二天的日期
time2=$(date -d '-2 days' +"%Y%m%d")
#获取前第三天的日期
time3=$(date -d '-3 days' +"%Y%m%d")

#如果存在数据
if [ -d ${targetpath}/${time1}/ ]
then
  #恢复数据
  mongorestore ${targetpath}/${time1}/
  #结束脚本
  exit
fi

#如果存在数据
if [ -d ${targetpath}/${time2}/ ]
then
  #恢复数据
  mongorestore ${targetpath}/${time2}/
  #结束脚本
  exit
fi

#如果存在数据
if [ -d ${targetpath}/${time3}/ ]
then
  #恢复数据
  mongorestore ${targetpath}/${time3}/
  #结束脚本  
  exit
fi
  • 恢复数据脚本说明
#恢复所有数据库到mongodb中:
mongorestore ${targetpath}/${time3}/
#恢复指定数据库:
mongorestore -d apk ${targetpath}/${time3}/apk/
  • 添加计划任务:crontab -e (看不懂这里请百度crontab)
#每天凌晨3点执行backup.bat
0 3 * * * /home/sam/mongodb/bat/backup.bat
#每天凌晨3点执行remove.bat
0 3 * * * /home/sam/mongodb/bat/remove.bat

提示:记得给你的bat文件获取权限: sudo chmod 777 ./backup.bat (不一一写出来了)。

原文地址:https://www.cnblogs.com/sanmu083/p/5591209.html