zoukankan      html  css  js  c++  java
  • 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;

    }

  • 相关阅读:
    【原创】解决向工程中添加Megacore 文件在文件列表中没有出现目标文件的问题
    (笔记)找工作,该怎么进补
    (原创)结构体位域操作
    (原创)TCP/IP学习笔记之IP(网际协议)
    (原创)确认大端模式或小端模式(最直接有效的方法)
    (原创)HDL中的unsigned与signed
    (原创)TCP/IP学习笔记之概述
    (笔记)往一个指定的地址读写一个值
    (笔记)我的EDN博客被评为专家博客啦
    (原创)同步复位与异步复位
  • 原文地址:https://www.cnblogs.com/weipeng/p/4256049.html
Copyright © 2011-2022 走看看