jericho0702 发表于 2015-12-22 14:47:42

shell定期清理mongodb数据

  需求:
  每天定时清除mongodb中某一天之前的数据
  思路:
  采用shell脚本调用mongodb的命令执行js脚本即可。
  步骤:
  1.编写email.js文件,作用:清除mongodb某天之前数据,具体代码如下:




[*]Date.prototype.format = function(format)

[*]{
[*]    var o =
[*]    {
[*]      "M+" : this.getMonth()+1, //month
[*]      "d+" : this.getDate(), //day
[*]      "h+" : this.getHours(), //hour
[*]      "m+" : this.getMinutes(), //minute
[*]      "s+" : this.getSeconds(), //second
[*]      "q+" : Math.floor((this.getMonth()+3)/3), //quarter
[*]      "S" : this.getMilliseconds() //millisecond
[*]    }
[*]    if(/(y+)/.test(format))
[*]      format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
[*]    for(var k in o)
[*]      if(new RegExp("("+ k +")").test(format))
[*]            format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
[*]    return format;
[*]}
[*]
[*]function getDay(day){
[*]    var today = new Date();
[*]    var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
[*]    today.setTime(targetday_milliseconds); //注意,这行是关键代码
[*]    var tYear = today.getFullYear();
[*]    var tMonth = today.getMonth();
[*]    var tDate = today.getDate();
[*]    tMonth = doHandleMonth(tMonth + 1);
[*]    tDate = doHandleMonth(tDate);
[*]    return tYear+"-"+tMonth+"-"+tDate+" 00:00:00";
[*]    }
[*]
[*]function doHandleMonth(month){
[*]    var m = month;
[*]    if(month.toString().length == 1){
[*]      m = "0" + month;
[*]      }
[*]    return m;
[*]    }
[*]
[*]
[*]var myDate = new Date();
[*]var datetime = myDate.format("yyyy-MM-dd 00:00:00");
[*]var pre7day = getDay(-7);
[*]print("today="+datetime+"deleteday="+pre7day);
[*]datetime= new Date(datetime);
[*]pre7day= new Date(pre7day);
[*]var count=db.Mail.find({'updateTime':{'$lt':pre7day}}).count();
[*]print("count="+count);
[*]db.Mail.remove({'updateTime':{'$lt':pre7day}});
[*]print('前7天邮件清理完毕...');
[*]exit

2. 编写shell脚本mongo_clean.sh代码如下:




[*]#!/bin/bash

[*]#清空mongodb中的前7天邮件: guoxin.ai@renren-inc.com
[*]
[*]/data/web/mongodb/mongodb-linux-x86_64-2.4.5/bin/mongo 10.3.18.80:27017/mail -quiet /data/web/email.js
  3.加入crontab中:
  10 0 * * * sh /data/web/agx/mongo_clean.sh
  

即完成shell操作mongodb执行定时任务,根据任务不同,修改对应的js文件。

参考文章:http://blog.csdn.net/alen1985/article/details/12712111
  
页: [1]
查看完整版本: shell定期清理mongodb数据