mongodb实现评论java_在Java中实现MongoDB的Group功能

在非关系型数据库MongoDB中,并没有任何现成的框架可以像SQL那样通过Group By就轻松实现数据库的分组功能。如果我们想要实现MongoDB的Group功能,就必须写原生态的NO-SQL查询语句来实现Group功能,这样既费时又费力,而且很容易出错,本文提供了一个封装的接口来实现MongoDB的Group功能,让程序员从此不再为MongoDB的Group而发愁。

接口方法如下:/**

* keyColumn : new String[]{"xxxName","xxxType"}

* condition : 查询条件 ,可为空

* initial : 分组统计初始变量,为空时自动为每列提供初始变量

* reduce : 记录处理function

* finalize : finalize函数,可为空

*/

public BasicDBList group(String[] keyColumn, DBObject condition,

DBObject initial, String reduce, String finalize) {

DBCollection coll = getCollection();

DBObject key = new BasicDBObject();

for (int i = 0; i < keyColumn.length; i++) {

key.put(keyColumn[i], true);

}

condition = (condition == null) ? new BasicDBObject() : condition;

if (StringUtils.isEmpty(finalize)) {

finalize = null;

}

if (initial == null) { //定义一些初始变量

initial = new BasicDBObject();

for (int i = 0; i < keyColumn.length; i++) {

DBObject index = new BasicDBObject();

index.put("count", 0);

index.put("sum", 0);

index.put("max", 0);

index.put("min", 0);

index.put("avg", 0);

index.put("self", "");

initial.put(keyColumn[i], index);

}

}

BasicDBList resultList = (BasicDBList) coll.group(key, condition,

initial, reduce, finalize);

return resultList;

}

实现案例:

//任务统计

@Action(value = "getTaskStatistic", results = { @Result(name = "success", type = "json", params = {

"includeProperties", "jsonResult" }) })

public String getTaskStatistic() {

DBObject initial = new BasicDBObject();

DBObject index = new BasicDBObject();

index.put("count", 0);

index.put("taskStatus", "");

initial.put("taskStatus", index);

String reduce = "function (doc, out) { "

+ " out.taskStatus.count = out.taskStatus.count+=1; "

+ " out.taskStatus.inspectStatus = doc.taskStatus;"

+ "}";

BasicDBList group = (BasicDBList) taskStatusService.group(new String[] { "taskStatus"}, null, initial, reduce, null);

this.jsonResult = group.toString();

return SUCCESS;

}

返回数据:[ { "taskStatus" : { "count" : 4.0 , "taskStatus" : "Finished"}} , { "taskStatus" : { "count" : 3.0 , "taskStatus" : "Received"}} , { "taskStatus" : { "count" : 2.0 , "taskStatus" : "UnReceive"}}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值