Chinaunix首页 | 论坛 | 博客
  • 博客访问: 692265
  • 博文数量: 143
  • 博客积分: 1554
  • 博客等级: 上尉
  • 技术积分: 1767
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-10 11:50
文章分类

全部博文(143)

文章存档

2017年(2)

2016年(5)

2015年(16)

2014年(25)

2013年(27)

2012年(16)

2011年(52)

分类: NOSQL

2015-03-17 13:38:49

需求

每天定时清除mongodb中某一天之前的数据

思路

采用shell脚本调用mongodb的命令执行js脚本即可。

步骤

1.编写email.js文件,作用:清除mongodb某天之前数据,具体代码如下:

点击(此处)折叠或打开

  1. Date.prototype.format = function(format)
  2. {
  3.     var o =
  4.     {
  5.         "M+" : this.getMonth()+1, //month
  6.         "d+" : this.getDate(), //day
  7.         "h+" : this.getHours(), //hour
  8.         "m+" : this.getMinutes(), //minute
  9.         "s+" : this.getSeconds(), //second
  10.         "q+" : Math.floor((this.getMonth()+3)/3), //quarter
  11.         "S" : this.getMilliseconds() //millisecond
  12.     }
  13.     if(/(y+)/.test(format))
  14.         format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
  15.     for(var k in o)
  16.         if(new RegExp("("+ k +")").test(format))
  17.             format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
  18.     return format;
  19. }

  20. function getDay(day){
  21.     var today = new Date();
  22.     var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
  23.     today.setTime(targetday_milliseconds); //注意,这行是关键代码
  24.     var tYear = today.getFullYear();
  25.     var tMonth = today.getMonth();
  26.     var tDate = today.getDate();
  27.     tMonth = doHandleMonth(tMonth + 1);
  28.     tDate = doHandleMonth(tDate);
  29.     return tYear+"-"+tMonth+"-"+tDate+" 00:00:00";
  30.     }

  31. function doHandleMonth(month){
  32.     var m = month;
  33.     if(month.toString().length == 1){
  34.         m = "0" + month;
  35.         }
  36.     return m;
  37.     }


  38. var myDate = new Date();
  39. var datetime = myDate.format("yyyy-MM-dd 00:00:00");
  40. var pre7day = getDay(-7);
  41. print("today="+datetime+"deleteday="+pre7day);
  42. datetime= new Date(datetime);
  43. pre7day= new Date(pre7day);
  44. var count=db.Mail.find({'updateTime':{'$lt':pre7day}}).count();
  45. print("count="+count);
  46. db.Mail.remove({'updateTime':{'$lt':pre7day}});
  47. print('前7天邮件清理完毕...');
  48. exit

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

点击(此处)折叠或打开

  1. #!/bin/bash
  2. #清空mongodb中的前7天邮件: guoxin.ai@renren-inc.com

  3. /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


阅读(4082) | 评论(0) | 转发(0) |
0

上一篇:mongo常用命令操作

下一篇:mongod日志切割

给主人留下些什么吧!~~