MongoDB
1 前言
一个问题,一篇文章,一出故事。
mongoDB的mongoexport工具貌似不支持整库导出,于是想到使用脚本实现。
由于了解到mongoDB的命令行客户端是一个JavaScript客户端,于是本章需要结合JavaScript技术实现,使用脚本前,建议你先阅读如下章节,
2 最佳实践
2.1 创建脚本
mkdir ~/scripts/ vim ~/scripts/mongoexportAllData.sh
加入如下配置,
#!/bin/bash mongoHost="localhost" mongoPort="27017" backupDir="/backup/comchatBackup/mongoExport" mongoExportLog="/var/log/mongodb/mongoExport.log" cd "$backupDir" if [ $? != 0 ]; then echo "`date '+%Y-%m-%d %H:%M:%S'` Backup storage '""$backupDir""' access failed!" | tee -a "$mongoExportLog" exit 0 fi if [ ! -d `dirname "$mongoExportLog"` ]; then mkdir -p `dirname "$mongoExportLog"` fi cat > getmongoDataList.js << EOF var dataBases=db.adminCommand('listDatabases').databases; dataBases.forEach(function(item){ var dataBase=item.name; db=db.getSiblingDB(dataBase); var collections=db.getCollectionNames(); for(x in collections){ collection=collections[x]; print(dataBase+"."+collection); } }) EOF echo "`date '+%Y-%m-%d %H:%M:%S'` Backup start!" | tee -a "$mongoExportLog" for i in `mongosh "$mongoHost:$mongoPort/test" getmongoDataList.js | grep -v :`; do dataBase=`echo "$i" | cut -d"." -f1` collection=`echo "$i" | cut -d"." -f2` mongoexport -h "$mongoHost" --port "$mongoPort" -d "$dataBase" -c "$collection" --type=json -o "$backupDir/$dataBase.$collection.json" if [ $? == 0 ]; then echo "`date '+%Y-%m-%d %H:%M:%S'` Backup $dataBase.$collection successfully!" | tee -a "$mongoExportLog" else echo "`date '+%Y-%m-%d %H:%M:%S'` Backup $dataBase.$collection failed!" | tee -a "$mongoExportLog" fi done rm -f getmongoDataList.js echo "`date '+%Y-%m-%d %H:%M:%S'` Backup end!" | tee -a "$mongoExportLog"
2.2 执行导出操作
sh ~/scripts/mongoexportAllData.sh
2.3 检查执行日志
cat /var/log/mongodb/mongoExport.log
没有评论