自动识别单点或副本集
            
            
              bash
              
              
            
          
          [root@centos610:/root]# ll
total 160
-rw-r--r--. 1 root root 65615 Aug 22 09:43 install.log
-rw-r--r--. 1 root root 20438 Aug 22 09:40 install.log.syslog
-rwxr-xr-x  1 root root  4997 Oct 29 15:56 mongobackup.sh
-rwxr-xr-x  1 root root   117 Aug 27 14:55 mongorestore.sh
[root@centos610:/root]# 
[root@centos610:/root]# ./mongobackup.sh
备份过程请查看 /rman/back_centos610_20251029_160547.log
[root@centos610:/root]# 
[root@centos610:/root]# cd /rman
[root@centos610:/rman]# 
[root@centos610:/rman]# ll
total 48
-rw-r--r-- 1 root   root     3944 Oct 29 16:07 back_centos610_20251029_160547.log
drwxr-xr-x 4 root   root       42 Oct 29 16:05 dump_centos610_20251029_160547
[root@centos610:/rman]# 
[root@centos610:/rman]# 
[root@centos610:/rman]# tail -50 back_centos610_20251029_160547.log
mongo备份开始:Wed Oct 29 16:05:47 CST 2025
# 单机配置 
2025-10-29T16:05:48.201+0800    writing admin.system.users to /rman/dump_centos610_20251029_160547/admin/system.users.bson.gz
2025-10-29T16:05:48.246+0800    done dumping admin.system.users (2 documents)
2025-10-29T16:05:48.247+0800    writing admin.system.version to /rman/dump_centos610_20251029_160547/admin/system.version.bson.gz
2025-10-29T16:05:48.293+0800    done dumping admin.system.version (2 documents)
2025-10-29T16:05:48.295+0800    writing test.fs.chunks to /rman/dump_centos610_20251029_160547/test/fs.chunks.bson.gz
2025-10-29T16:05:48.296+0800    writing test.fs.files to /rman/dump_centos610_20251029_160547/test/fs.files.bson.gz
2025-10-29T16:05:48.297+0800    writing test.test_collection to /rman/dump_centos610_20251029_160547/test/test_collection.bson.gz
2025-10-29T16:05:48.338+0800    done dumping test.test_collection (1 document)
2025-10-29T16:05:48.428+0800    done dumping test.fs.files (1562 documents)
2025-10-29T16:05:50.893+0800    [........................]  test.fs.chunks  172/5317  (3.2%)
2025-10-29T16:05:53.893+0800    [#.......................]  test.fs.chunks  404/5317  (7.6%)
2025-10-29T16:05:56.892+0800    [##......................]  test.fs.chunks  585/5317  (11.0%)
2025-10-29T16:05:59.893+0800    [###.....................]  test.fs.chunks  783/5317  (14.7%)
2025-10-29T16:06:02.893+0800    [####....................]  test.fs.chunks  1036/5317  (19.5%)
2025-10-29T16:06:05.893+0800    [#####...................]  test.fs.chunks  1260/5317  (23.7%)
2025-10-29T16:06:08.893+0800    [######..................]  test.fs.chunks  1454/5317  (27.3%)
2025-10-29T16:06:11.892+0800    [#######.................]  test.fs.chunks  1639/5317  (30.8%)
2025-10-29T16:06:14.893+0800    [########................]  test.fs.chunks  1832/5317  (34.5%)
2025-10-29T16:06:17.893+0800    [#########...............]  test.fs.chunks  2040/5317  (38.4%)
2025-10-29T16:06:20.893+0800    [#########...............]  test.fs.chunks  2205/5317  (41.5%)
2025-10-29T16:06:23.893+0800    [##########..............]  test.fs.chunks  2347/5317  (44.1%)
2025-10-29T16:06:26.893+0800    [##########..............]  test.fs.chunks  2347/5317  (44.1%)
2025-10-29T16:06:29.893+0800    [##########..............]  test.fs.chunks  2347/5317  (44.1%)
2025-10-29T16:06:32.893+0800    [##########..............]  test.fs.chunks  2381/5317  (44.8%)
2025-10-29T16:06:35.893+0800    [###########.............]  test.fs.chunks  2580/5317  (48.5%)
2025-10-29T16:06:38.892+0800    [############............]  test.fs.chunks  2797/5317  (52.6%)
2025-10-29T16:06:41.893+0800    [#############...........]  test.fs.chunks  2999/5317  (56.4%)
2025-10-29T16:06:44.893+0800    [##############..........]  test.fs.chunks  3216/5317  (60.5%)
2025-10-29T16:06:47.894+0800    [###############.........]  test.fs.chunks  3424/5317  (64.4%)
2025-10-29T16:06:50.893+0800    [################........]  test.fs.chunks  3621/5317  (68.1%)
2025-10-29T16:06:53.893+0800    [#################.......]  test.fs.chunks  3778/5317  (71.1%)
2025-10-29T16:06:56.893+0800    [#################.......]  test.fs.chunks  3778/5317  (71.1%)
2025-10-29T16:06:59.893+0800    [#################.......]  test.fs.chunks  3824/5317  (71.9%)
2025-10-29T16:07:02.893+0800    [##################......]  test.fs.chunks  4114/5317  (77.4%)
2025-10-29T16:07:05.893+0800    [###################.....]  test.fs.chunks  4314/5317  (81.1%)
2025-10-29T16:07:08.893+0800    [####################....]  test.fs.chunks  4541/5317  (85.4%)
2025-10-29T16:07:11.893+0800    [#####################...]  test.fs.chunks  4734/5317  (89.0%)
2025-10-29T16:07:14.893+0800    [######################..]  test.fs.chunks  4962/5317  (93.3%)
2025-10-29T16:07:17.893+0800    [#######################.]  test.fs.chunks  5204/5317  (97.9%)
2025-10-29T16:07:19.359+0800    [########################]  test.fs.chunks  5317/5317  (100.0%)
2025-10-29T16:07:26.322+0800    done dumping test.fs.chunks (5317 documents)
mongo备份完成:Wed Oct 29 16:07:26 CST 2025
            
            
              bash
              
              
            
          
          #!/bin/bash
#==============================================================#
# File    :  mongobackup.sh                                    #
# Ctime   :  2022-01-20                                        #
# Mtime   :  2025-10-28                                        #
# Desc    :  Mongodb Database Backup                           #
# Version :  3.0.0                                             #
# Author  :  楚枫默寒                                          #
# Copyright (C) 2022-2099                                      #
#==============================================================#
# 检查是否以root身份运行
if [[ $EUID -ne 0 ]]; then
    echo "此脚本必须以root权限运行!"
    exit 1
else
    ALTIME=$(date +%Y%m%d_%H%M%S)
    BACKPATH=/rman
    FILEPATH=dump_$(hostname)_${ALTIME}
    LOGFILE=back_$(hostname)_${ALTIME}.log
fi
color_setting(){
    RC='\033[31;1m'        #红色 error
    GC='\033[32;1m'        #绿色 success
    YC='\033[33;1m'        #黄色 warning
    BC='\033[34;1m'        #蓝色 output
    DC='\033[35;1m'        #粉色 detail
    AC='\033[36;1m'        #天蓝 info
    EC='\033[0m'           #黑白 EC
}
#提取副本集名称
pro_conf(){
    HOST=$(/sbin/ip addr |egrep -v  "127|0.0.0.0|00.00.00.00|lo:0|00:|:"| egrep -o '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}'| head -n 1|awk '{print $1}')
    PORT=$(netstat -an|grep mongo|awk '{print $9}'| sed 's/[^0-9]*//g')
    # 如果需要认证,填写用户名
    USERNAME="userxxxx"
    # 如果需要认证,填写密码
    PASSWORD="passxxxx"
    # 认证数据库,通常是admin
    AUTH_DB="admin"
    # 认证
    AUTH=${USERNAME}:${PASSWORD}
    
    #提取conf文件
    conf_file=$(ps -ef|egrep "mongo|mongod.conf|mongodb.conf"|grep -v grep|awk -F '-f ' '{print $2}'|awk -F ' ' '{print $1}')
    #显示副本集名称
    replSet=$(cat ${conf_file}|tr -d ' '|grep replSet|egrep -v "^#")
    if [[ -n ${replSet} ]];then
        if [[ ${replSet} =~ ":" ]];then
            repl_name=$(echo $replSet|grep -v '^#'|awk -F ':' '{print $2}'|tr -d ' '|cut -d'#' -f1)
        elif [[ ${replSet} =~ "=" ]];then
            repl_name=$(echo $replSet|grep -v '^#'|awk -F '=' '{print $2}'|tr -d ' '|cut -d'#' -f1)
        fi
    else
        repl_name=''
    fi
}
#提取库名
#get_dbname(){
#    local repl_name=$1
#    if [[ -n $1 ]];then
#        # 构建连接字符串
#        #db_name=$(mongo "mongodb://${USERNAME}:${PASSWORD}@${HOSTS}/?replicaSet=${repl_name}&authSource=${AUTH_DB}" --quiet --eval "db.adminCommand('listDatabases').databases.map(db => db.name)"|grep -v NETWORK|sed 's/^\[//;s/\]$//;s/,/\n/g'|sed 's/"//g'|sed '/^$/d'|sort)
#        db_name=$(echo "show dbs" | mongo "mongodb://${AUTH}@${HOST}:${PORT}/?replicaSet=${repl_name}&authSource=${AUTH_DB}"|egrep -v "NETWORK|^bye$"|awk 'NR>3{print $1}'|grep -v "^MongoDB$")
#    else #单实例
#        db_name=$(echo "show dbs" | mongo "mongodb://${AUTH}@${HOST}:${PORT}/?authSource=${AUTH_DB}"|egrep -v "NETWORK|^bye$"|awk 'NR>3{print $1}'|grep -v "^MongoDB$")
#    fi
#}
#备份过程
back_process(){
    echo -e "${DC}备份过程请查看 ${BACKPATH}/${LOGFILE}${EC}"
    
    CMD=$(which mongodump)
    CMD_V=$(${CMD} --version|grep "mongodump version:"| awk -F '[^0-9]+' '{print $2}')
    echo -e ${GC}"mongo备份开始:"${AC}$(date)${EC} >> ${BACKPATH}/${LOGFILE}
    if [[ -n ${repl_name} ]];then
        echo -e ${RC}"# 副本集配置 "${EC} >> ${BACKPATH}/${LOGFILE}
        case ${CMD_V} in
            3)
                ${CMD} --uri="mongodb://${AUTH}@${HOST}:${PORT}/?replicaSet=${repl_name}&authSource=${AUTH_DB}" -o ${BACKPATH}/${FILEPATH}        >> ${BACKPATH}/${LOGFILE} 2>&1 ;;
            *)
                ${CMD} --uri="mongodb://${AUTH}@${HOST}:${PORT}/?replicaSet=${repl_name}&authSource=${AUTH_DB}" -o ${BACKPATH}/${FILEPATH} --gzip >> ${BACKPATH}/${LOGFILE} 2>&1 ;;
        esac
    else
        echo -e ${RC}"# 单机配置 "${EC} >> ${BACKPATH}/${LOGFILE}
        case ${CMD_V} in
            3)
                ${CMD} --host ${HOST}:${PORT} -u${USERNAME} -p${PASSWORD} --authenticationDatabase ${AUTH_DB} -o ${BACKPATH}/${FILEPATH}        >> ${BACKPATH}/${LOGFILE} 2>&1 ;;
            *)
                ${CMD} --host ${HOST}:${PORT} -u${USERNAME} -p${PASSWORD} --authenticationDatabase ${AUTH_DB} -o ${BACKPATH}/${FILEPATH} --gzip >> ${BACKPATH}/${LOGFILE} 2>&1 ;;
        esac
    fi
    echo -e ${GC}"mongo备份完成:"${AC}$(date)${EC} >> ${BACKPATH}/${LOGFILE}
}
#清理日志
clear_log(){
    REDUNDANCY=2
    rmdir_no=$(find $BACKPATH -maxdepth 1 -type d -name "dump_*"|sort|tail -n $REDUNDANCY|wc -l)
    if [ $rmdir_no -ge 2 ];then
        rmdir=$(find $BACKPATH -maxdepth 1 -type d -name "dump_*"|sort|tail -n $REDUNDANCY|head -n 1);
        if [ $rmdir ];then
            rm -rf $rmdir;
        fi
    fi
    find $BACKPATH -type f -name "back_*.log" -mtime +10 -delete
}
main(){
    color_setting
    pro_conf
    back_process
    clear_log
}
main "$@"