参考
mongoDB:读取,根据oplog查找时间戳:https://devpress.csdn.net/mongodb/6304939fc67703293080d1cb.html
mongodb 备份指定时间段的数据:https://blog.51cto.com/u_16213337/7146774
MongoDB备份以及还原(全量+增量):https://devpress.csdn.net/mongodb/6304939fc67703293080d1cb.html
为什么oplogReplay参数只设置了日志应用结束时间oplogLimit,而没有设置开始时间?:https://www.cnblogs.com/lijiaman/p/13531574.html
mongodb oplog日志详解和格式分析 :https://www.cnblogs.com/xinghebuluo/p/15003040.html
MongoDB备份与恢复 + 导出csv格式 :https://zhuanlan.zhihu.com/p/163255094?utm_id=0
MongoDB添加--query查询:无效的JSON输入:https://cloud.tencent.com/developer/ask/sof/1197629
MongoDB的备份与恢复:https://www.cnblogs.com/clsn/p/8244206.html#auto-id-12
查看bson文件可以先将bson文件转为json
bsondump cook.bson --outFile=cook.json
完整代码:dbBackupContinue.js
思路:每天0点先全量备份,之后每隔1小时增量备份1个小时多的数据
补充:副本集若开了访问权限,需要在下方每个指令中加上: -u 用户名 -p 密码 --authenticationDatabase 权限存放库
/**
* 每小时增量备份
*/
const { printLog } = require("../utils/printlog");
var path = require("path"),
fs = require("fs-extra"),
exec = require("child_process").exec,
_ = require("lodash"),
async = require("async"),
moment = require("moment"),
config = {
dateFormate: "YYYYMMDD",
dbBackupPath: "/tmp/backup",
suffix: "",
days: 3,
tarExt: ".zip",
tar: true,
},
Backup = {};
/**
* [init 数据库备份服务]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
Backup.init = function (options) {
return new Promise((resolve, reject) => {
var dbBackupPath = options.path || config.dbBackupPath, //数据库备份父级目录
dbHost = options.host, //数据连接
dbName = options.name, //数据库名称
suffix = options.suffix || config.suffix, //存储目录后缀
dateFormate = options.dateFormate || config.dateFormate, //今日备份目录名的时间标示
todayBackUpName = getDatePath(dbName, new Date(), suffix, dateFormate), //今日备份目录名
todayBackUpPath = path.join(dbBackupPath, todayBackUpName);
if (!dbHost) {
printLog("[参数缺失] dbHost");
return;
}
if (!dbName) {
printLog(`[备份数据库] 所有库`);
} else {
printLog(`[备份数据库] ${dbName}`);
}
if (!fs.existsSync(dbBackupPath)) {
//创建数据库备份父级目录
fs.mkdirsSync(dbBackupPath);
}
// if (fs.existsSync(todayBackUpPath)) {
// printLog('[已经创建] %s', todayBackUpPath);
// return;
// }
console.info(todayBackUpPath);
//首次全量备份
if (!fs.existsSync(todayBackUpPath)) {
printLog("【全量备份】");
printLog(dbHost + " : " + dbName ? dbName : "所有库", "开始备份");
var cmdStr =
"mongodump -h " +
dbHost +
(dbName ? " -d " + dbName : "") +
" -o " +
todayBackUpPath;
printLog(
"-------------------------------------------- 1.备份全量数据 -------------------------------------------"
);
printLog(cmdStr, "执行全量备份指令");
exec(cmdStr, function (err) {
if (!err) {
printLog(todayBackUpPath, "全量备份成功");
console.log(
"-------------------------------------------- 2.清理过期备份数据 -------------------------------------------"
);
printLog(dbBackupPath, "清理过期的备份库");
//清理历史数据
var currentPaths = fs.readdirSync(dbBackupPath),
effectPaths = getDaysInnerPath(
dbName,
suffix,
dateFormate,
options.days || config.days
);
printLog(effectPaths, "有效文件名:");
printLog(currentPaths, "当前目录文件列表:");
printLog(
effectPaths[1] + "~" + effectPaths[effectPaths.length - 1],
"保留数据"
);
for (var i = 0, len = currentPaths.length; i < len; i++) {
if (
currentPaths[i].indexOf(dbName ? dbName : "all") > -1 &&
_.indexOf(effectPaths, currentPaths[i]) < 0
) {
var rmFile = path.join(dbBackupPath, currentPaths[i]);
printLog("待删除文件路径:" + rmFile);
exec("rm -rf " + rmFile, function (err) {
if (!err) {
console.log("[清理过期指定数据库备份文件] %s 成功", rmFile);
} else {
console.log(err);
console.info("[清理过期指定数据库备份文件] %s 失败", rmFile);
}
});
}
}
printLog("[备份成功]————[过期数据备份清理成功]~~");
resolve();
} else {
console.log("[备份失败] %s", err);
reject(err);
}
});
} else {
//每小时增量备份
//此命令要用秒去查询
//=============================================
var spikeName = moment(new Date()).format("YYYYMMDDHH"); //增量备份目录名
var endTime = Math.round(new Date().getTime() / 1000); //当前时间
var startTime = endTime - ( 1 * 60 * 60 + 5 * 60 ); //往前推1小时+5分钟
printLog(spikeName, "增量备份");
var hoursCmd = `mongodump -h ${dbHost} -d local -c oplog.rs -q \'{"ts":{"$gte":{"$timestamp":{"t":${startTime},"i":0}},"$lte":{"$timestamp":{"t":${endTime},"i":0}}}}\' -o ${todayBackUpPath}/${spikeName}`;
exec(hoursCmd, function (err) {
if (!err) {
printLog(spikeName, "增量备份成功");
resolve();
} else {
printLog(spikeName, "增量备份失败");
console.info(err.message);
reject(err);
}
});
}
});
};
function getDatePath(dbName, date, suffix, dateFormate) {
var dir = moment(date).format(dateFormate);
return `${dir}-${dbName ? dbName : "all"}${suffix ? "-" + suffix : ""}`;
}
//获取几天内的目录
function getDaysInnerPath(dbName, suffix, dateFormate, days) {
days = days || 1;
var now = new Date(),
pathArray = [];
for (var i = days - 1; i >= 0; i--) {
var pathName = getDatePath(
dbName,
new Date(now.getTime() - i * 24 * 60 * 60 * 1000),
suffix,
dateFormate
);
pathArray.push(pathName);
pathArray.push(pathName + config.tarExt);
}
return pathArray;
}
module.exports = Backup;