用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 '+dumperr+' '+dumpout); if(!dumperr){ shenjiauditlogTestCollection.rename('auditOrigData'+yymmdd+'-'+todayyymmdd,function(renameerr,renameinfo){ console.log('rename '+renameerr+' '+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+ '+reserr+' '+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: ' + error+" "); sys.print('stdout: ' + stdout+" "); sys.print('stderr: ' + stderr+" "); callback(error,stdout); }); }