Skip to content

Instantly share code, notes, and snippets.

@dead-horse
Created November 13, 2012 03:29
Show Gist options
  • Save dead-horse/4063766 to your computer and use it in GitHub Desktop.
Save dead-horse/4063766 to your computer and use it in GitHub Desktop.
mongodb数据库定时备份
/*!
* dump.js, dump mongodb.
* Copyright(c) 2012 Taobao.com
* Author: busi.hyy <busi.hyy@taobao.com>
*
* 每天凌晨3点从mongo dump一份到指定文件夹,前缀为20121113_
* 只保留最近七天的dump文件
* Example: `node dump 127.0.0.1:27071 back database collection1 collection2 ...`
*/
/**
* module dependences
*/
var fs = require('fs');
var spawn = require('child_process').spawn;
var argv = process.argv;
var mongoHost = process.argv[2];
var baseDirName = process.argv[3];
var database = process.argv[4];
var keepTime = 7 * 24 * 3600 * 1000; //保存七天的备份
function getDateString(date) {
if (typeof date === 'number') {
date = new Date(date);
}
return String(date.getFullYear()) + (date.getMonth() + 1) + date.getDate();
}
function handleDump(now) {
var collectionIndex = 5;
var removeDir = getDateString(now.getTime() - keepTime) + '_' + baseDirName;
doDump(collectionIndex, now);
if (fs.existsSync(removeDir)) {
spawn('rm', ['-rf', removeDir]);
}
}
function doDump(index, now) {
var saveDir = getDateString(now) + '_' + baseDirName;
var dumpArgvs = ['-h', mongoHost, '-o', saveDir];
if (database) {
dumpArgvs = dumpArgvs.concat(['-d', database]);
var collection = process.argv[index];
if (collection) {
dumpArgvs = dumpArgvs.concat(['-c', collection]);
}
}
spawn('mongodump', dumpArgvs).on('exit', function (code) {
if (process.argv[++index]) {
doDump(index, now);
}
});
}
setInterval(function () {
var now = new Date();
if (now.getHours() === 3) { //凌晨三点进行备份
handleDump(now);
}
}, 60 * 60 * 1000);
@fengmk2
Copy link

fengmk2 commented Nov 13, 2012

数据量有多大?还要看看当前磁盘容量是否能装得下。
不是所有表都dump吧?指定要dump那些数据库。

@dead-horse
Copy link
Author

修改了。 可以指定数据库指定collections.

@fengmk2
Copy link

fengmk2 commented Nov 14, 2012

好吧,部署上去吧。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment