之前写一些mongodb的同步或操作程序,往往使用perl,甚至c实现,这样程序很繁琐,而且逻辑不好控制,甚至一些功能和命令什么的,在这些语言的mongo驱动中就没有实现。后来发现mongodb 的shell是javascript实现的,如果直接使用js实现相应的功能则显得很直观和简便。
首先在js中可以直接使用mongo的命令,而不用像在c中那样用bson之类的拼接各类语句。比如在js中可以直接这样写:
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;
}
var myDate = new Date();
var datetime = myDate.format("yyyy-MM-dd hh:mm:ss");
print(datetime);
var cursor = db.my_soft_info.find({"percent":0,"starttime":{$lt: datetime},"endtime":{$gt: datetime}});
while(cursor.hasNext())
{
var temp = cursor.next();
print(tojson(temp.bookid));
var arr = db.soft_basic_info.findOne({"id":temp.uid},{softcount:1});
db.soft_basic_info.update({"id":temp.uid},{$set:{"freedate":arr.softcount+1,"getgrade":3}});
}
然后可以在mongo中直接调用js脚本,或者在shell脚本中使用,如果在shell脚本中使用js脚本,再配合crontab等定时任务工具,可以当作mongodb的计划任务服务程序。
在shell中使用js脚本可以直接这样写。很是方便
mongo host:port/dbname --shell jsname.js;
|