zoukankan      html  css  js  c++  java
  • mongodb---js脚本操作速记

         之前写一些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;
  • 相关阅读:
    Java Generics and Collections-2.2
    Java Generics and Collections-2.1
    Java Generics and Collections-8.1
    oracle 倒库后insert id冲突的问题
    第十章 基本数据结构 练习 10.4-4
    第十章 基本数据结构 练习 10.4-2
    第十章 基本数据结构 练习 10.4-3
    第九章 中位数和顺序统计量 9.2 期望为线性时间的选择算法
    Log4j2的基本使用
    JSF页面中的JS取得受管bean的数据(受管bean发送数据到页面)
  • 原文地址:https://www.cnblogs.com/OSLover/p/3251294.html
Copyright © 2011-2022 走看看