初探mongo之备份还原

由于之前一直使用的是mysql,现在换成了mongo,一开始不太适应。第一个练手项目选择了mongo备份和还原。

#!/bin/bash
#creates backup files(bson) of given MongoDB or collections on a given server
#mongo dump and tar the output into a file named dbname_date.ex: dbname_201610241655.tar.gz
#by keith_testing 


#setting of  server 
Host="127.0.0.1"
Port="27017" #default mongo port
UserName="xxx"
PassWord="xxx"


#auto detect mongodump and mongorestore bin path
Mongodump_Bin_path="$(which mongodump)"
Mongoretore_Bin_path="$(which mongorestore)"


Date=$(date -d '+0 dayes' +%Y%md%H%M)
Backup_DB_Name="xxxx"
Tar_Backup_File_Name=$Backup_DB_Name"_"$Date".tar.gz"


#set backup path
Backup_Path="/backup"
Tmp_Backup_Path="/tmpbackup"
Tmp_Backup_Dir=$Tmp_Backup_Path/$Date   #mongodump output file path


#backup collections array
#add --quiet help hidden mongo output info ,or array will contains the mongo info ,such as mongo version ,connection info 
#grep -v "^log_"  means array donot contains the collection which start with "log_".ex "log_role_level "
collections_arr=`echo "show collections; " | mongo $Backup_DB_Name --quiet | grep -v "^log_"`


#create backup path if it does not exist
if [ ! -d $Backup_Path ];then
    mkdir -p $Backup_Path
fi


if [ ! -d $Tmp_Backup_Path];then
    mkdir -p $Tmp_Backup_Path
fi


if [ -d "$Backup_Path " ];then
    cd $Backup_Path 
    for collection in ${collections_arr}
    do
        #--authenticationDatabase admin,if it doesnot work ,add it 
        $Mongodump_Bin_path --hot $Host:$Port -u $UserName -p $PassWord -d $Backup_DB_Name -c $collection --authenticationDatabase admin --out $Tmp_Backup_Dir/ >>/dev/null
    done


    if [ -d "$Tmp_Backup_Dir" ];then
        tar -zcvf $Backup_Path/$Tar_Backup_File_Name -C $Tmp_Backup_Dir . >>/dev/null
        if [ $? = 0 ];then
            rm -rf $Tmp_Backup_Dir/*
            echo "Backup sucess:`du -sh $Tar_Backup_File_Name`"
            echo "Output file path : $Backup_Path/$Tar_Backup_File_Name"
        else
            echo "Could not create tar file : $Backup_Path/$Tar_Backup_File_Name"
        fi
    else
        echo "Could not dump mongo db collections to $Tmp_Backup_Dir";echo;
else
    "Could not find path : $Backup_Path,fail to backup"
fi


#restore the collections
#it will not work ,if it has no --host param 
#--drop clear the colletion ,and then restore the collection
#Restore_Path is the direction which contains the files *.bson and *.json
#Restore_Path:you can tar -zxvf $Tar_Backup_File_Name -C Restore_Path
Restore_Path="restore"

$Mongoretore_Bin_path --host $Host -d $Backup_DB_Name --drop $Restore_Path


期间碰到了挺多问题,不过mongo --help或mongodump --help和谷歌一起解决了不少的问题

致清除了的坑


你可能感兴趣的:(shell_mongo)