首页 > 代码库 > mongdb高级操作(group by )
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 = http://www.mamicode.com/(BasicDBObject) rs.get(0);
return Double.parseDouble(data.get("avg").toString());} return 0.0;
}
mongdb高级操作(group by )