每个月执行一次任务,保存90天的mongo日志数据

用mongo 的dump 和 restore实现

shell版 

#!/bin/bash
mongodump --host 127.0.0.1 --port 27017 -d lewifi -c auditOrigData -q {time:{\$gt:1423478000}} -o ~/auditmongologchange
mongo <<EOF
use lewifi
db.auditOrigData.renameCollection('auditOrigData_back')
EOF
echo "restore"
mongorestore -h 127.0.0.1 --port 27017 --db lewifi  ~/auditmongologchange/lewifi/
rm -rf ~/auditmongologchange

 

nodejs版 主要代码

Task.prototype.backandChangeauditOrigData = function(){
    var starttoday=new Date();
    var todayyymmdd=tool.getYYMMDD(starttoday);
    starttoday.setDate(starttoday.getDate()-180);
    var datenum=tool.getDateCurTs(starttoday);
    var yymmdd=tool.getYYMMDD(starttoday);
    var dumpcommand='mongodump --host 127.0.0.1 --port 27017 -d lewifi -c auditOrigData -q {time:{\\$gt:'+datenum+'}} -o /Users/cdpmac/auditmongologchange';
    auditApi.execMonoOperaCommand(dumpcommand,function(dumperr,dumpout){
        console.log('dump\n'+dumperr+'\n'+dumpout);
        if(!dumperr){
            shenjiauditlogTestCollection.rename('auditOrigData'+yymmdd+'-'+todayyymmdd,function(renameerr,renameinfo){
                console.log('rename\n'+renameerr+'\n'+JSON.stringify(renameinfo));
                var restorecommand='mongorestore -h 127.0.0.1 --port 27017 --db lewifi  /Users/cdpmac/auditmongologchange/lewifi/';
                auditApi.execMonoOperaCommand(restorecommand,function(reserr,resout){
                        console.log('restore+\n'+reserr+'\n'+resout);
                        auditApi.execMonoOperaCommand('rm -rf /Users/cdpmac/auditmongologchange',function(rmerr,rmout){
                        })
                    }
                )
            })
        }
    });
}
execMonoOperaCommand内容
var exec = require('child_process').exec;

function execMonoOperaCommand(command, callback) {
    child = exec(command, function(error, stdout, stderr) {
        sys.print('error: \n' + error+"\n");
        sys.print('stdout: \n' + stdout+"\n");
        sys.print('stderr: \n' + stderr+"\n");
        callback(error,stdout);
    });
}

 

 
posted @ 2015-05-20 17:27  cclient  阅读(753)  评论(0编辑  收藏  举报