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;

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值