Home >Database >Mysql Tutorial > 在Java中实现MongoDB的Group功能

在Java中实现MongoDB的Group功能

WBOY
WBOYOriginal
2016-06-07 17:38:312019browse

在非关系型数据库MongoDB中,并没有任何现成的框架可以像SQL那样通过GroupBy就轻松实现数据库的分组功能。如果我们想要实现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

实现案例:

//任务统计 @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"}}]


本文出自 “尘风随影的天空” 博客,请务必保留此出处

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn