• mongdb高级操作(group by )


    首先介绍哈方法

    /** * 利用java驱动自带函数分组查询 *

    @param key 用来分组文档的字段 【group by key】 *

    @param cond 执行过滤的条件 【where name=? and age=?】 *

    @param initial reduce中使用变量的初始化 * @param reduce reduce(参数:当前文档和累加器文档.) *

    @param fn 结束后执行函数 *

    @return */

    参考例子1:

    group(DBObject key,DBObject cond,DBObject initial,String reduce,String fn ){

                 //key:用来分组文档的字段。和keyf两者必须有一个 [类似于group by]

                 BasicDBObject key = new BasicDBObject(); key.put("optCode", true);

                 //执行过滤的条件 [类似于where]

                 BasicDBObject[] array={ new BasicDBObject("startTimeLong",

                 new BasicDBObject("$gte", startTime)),

                 new BasicDBObject("startTimeLong", new BasicDBObject("$lte", endTime)) };

                 BasicDBObject cond = new BasicDBObject(); //cond.put("$and",array);

                 //initial:reduce中使用变量的初始化

                 BasicDBObject initial = new BasicDBObject();

                 initial.append("count", 0);

                 //reduce(当前文档和累加器文档.)

                 String reduce = "function(doc, aggr){" + " aggr.count += 1;" + " }";

                 String fn = null;            

                 dao.group(key, cond, initial, reduce, fn);

     }

    参考例子2:

     //求总数和平局数

    public Double findAverage(String sumField, String groupField, BasicDBObject where)

     {

              // 分组项字段 【group by groupField】

              DBObject key = new BasicDBObject(groupField, null)

             // 结果数据计数器 【select avg,rsdata.sum,rsdata.count 】

              BasicDBObject counter = new BasicDBObject();

             DBObject index = new BasicDBObject();

             index.put("count", 0);

             index.put("sum", 0);

             counter.put("rsdata", index);counter.put("avg", 0);}

             // reduce处理函数

             String procFunction = "function(doc,aggr){" + "aggr.rsdata.sum+=parseFloat(doc." + sumField + ");" + "aggr.rsdata.count+=1;" + "}";

             // 结果处理函数

             String finallyFunction = "function(doc){" + "doc.avg=doc.rsdata.sum/doc.rsdata.count;" + "}";

             BasicDBList rs = (BasicDBList) getCollection().group(key, where, counter, procFunction, finallyFunction);

             if (null != rs && rs.size() > 0)

             {BasicDBObject data = (BasicDBObject) rs.get(0);

             return Double.parseDouble(data.get("avg").toString());} return 0.0;

    }

  • 相关阅读:
    JavaScript之事件委托
    js中的事件委托(事件代理)详解
    CentOS已经安装命令,但提示找不到
    在Linux下创建7种类型的文件
    python源码安装的包的卸载
    新建文件所属组设置
    FFmpeg基础
    微服务架构概念
    一台 Java 服务器可以跑多少个线程?
    「学习的真正作用」​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​写出我心(一百三十八)
  • 原文地址:https://www.cnblogs.com/weipeng/p/4256049.html
Copyright © 2020-2023  润新知