原文:http://blog.csdn.net/congcong68/article/details/45012717

一.简介

db.collection.group()使用JavaScript,它受到了一些性能上的限制。大多数情况下,$ group在Aggregation Pipeline提供了一种具有较少的限制适用的替代。可以通过指定的键的集合中的文档和执行简单的聚合函数。在2.2版本中,返回的数组可以包含最多20000个元素;即最多20000个独特的分组。

我们比较熟悉的group by 的sql语句select key from table  groupby key,而mongoDB没提供SQL那样通过Group By就轻松实现数据库的分组功能,我们通过接口来实现的

db.collection.group({ key, reduce, initial[, keyf] [, cond] [, finalize] })

key

作为分组的key

reduce

一个聚合函数操作文档的分组操作期间。这些函数可以返回一个sum或count。该函数接受两个参数:当前文档和这个群体聚集的结果文档。

initial

初始化聚合结果文档变量,为空时自动为每列提供初始变量。

keyf

可选。替代的key 字段。指定一个函数创建一个“key object”作为分组的key。使用keyf而是通过group by领域而不是现有的文档域键组。

cond

过滤条件

finalize

在db.collection.group()返回最终结果之前,此功能可以修改的结果文档或替换的结果文档作为一个整体。

二.Mongo VUE操作Group By

1.MonogoDB数据库中添加了订单的数据

  1. /* 0 */
  2. {
  3. "_id" : ObjectId("552a330e05c27486b9b9b650"),
  4. "_class" : "com.mongo.model.Orders",
  5. "onumber" : "002",
  6. "date" : ISODate("2014-01-03T16:03:00Z"),
  7. "cname" : "zcy",
  8. "item" : {
  9. "quantity" : 1,
  10. "price" : 4.0,
  11. "pnumber" : "p002"
  12. }
  13. }
  14. /* 1 */
  15. {
  16. "_id" : ObjectId("552a331d05c275d8590a550d"),
  17. "_class" : "com.mongo.model.Orders",
  18. "onumber" : "003",
  19. "date" : ISODate("2014-01-04T16:03:00Z"),
  20. "cname" : "zcy",
  21. "item" : {
  22. "quantity" : 10,
  23. "price" : 2.0,
  24. "pnumber" : "p001"
  25. }
  26. }
  27. /* 2 */
  28. {
  29. "_id" : ObjectId("552a333105c2f28194045a72"),
  30. "_class" : "com.mongo.model.Orders",
  31. "onumber" : "003",
  32. "date" : ISODate("2014-01-04T16:03:00Z"),
  33. "cname" : "zcy",
  34. "item" : {
  35. "quantity" : 30,
  36. "price" : 4.0,
  37. "pnumber" : "p002"
  38. }
  39. }
  40. /* 3 */
  41. {
  42. "_id" : ObjectId("552a333f05c2b62c01cff50e"),
  43. "_class" : "com.mongo.model.Orders",
  44. "onumber" : "004",
  45. "date" : ISODate("2014-01-05T16:03:00Z"),
  46. "cname" : "zcy",
  47. "item" : {
  48. "quantity" : 5,
  49. "price" : 4.0,
  50. "pnumber" : "p002"
  51. }
  52. }

2.MongoDB实现分组并统计

  1)我们要对日期和产品编码进行分组,并计算相同的产品的数量

Sql语句:Select date, pnumber,sum(quantity) as total from orders,items group by date, pnumber(少了两张表的关联的条件)

MongoDB:

db.orders.group({

key: { date:1,'item.pnumber':1},

initial : {"total":0},

reduce : function Reduce(doc, out) {

out.total+=doc.item.quantity

} });

结果:

 2)实现一天卖出了多少个产品,金额是多少,平均价格是多少

db.orders.group({

key: {date:1},

initial :{"total":0,"money":0},

reduce : function Reduce(doc, out) {

out.total+=doc.item.quantity;

out.money+=doc.item.quantity*doc.item.price;

},

finalize : function Finalize(out) {

out.avg=out.money/out.total

returnout;

}

});

结果:

3)keyf的使用

keyf 对日期进行处理并以作为key来进来分组

db.orders.group({

keyf: function (doc){

return{'month':doc.date.getMonth()+1};

},

initial :{"total":0,"money":0},

reduce : function Reduce(doc, out) {

out.total+=doc.item.quantity;

out.money+=doc.item.quantity*doc.item.price;

},

finalize : function Finalize(out) {

out.avg=out.money/out.total

returnout;

}

});

结果:

三.Java MongoDB 实现

       Spring Data MongoDB提供了Group有几个接口
       
   
    GroupCommand  groupCommand=new GroupCommand(inputCollection, keys, condition, initial, reduce, finalize);
 

1)我们要对日期和产品编码进行分组,并计算相同的产品的数量

           

  1. <strong>  </strong>     @Override
  2. public void getGroupCount(String collectionName) {
  3. BasicDBObject key = new BasicDBObject();
  4. key.put("date", 1);
  5. key.put("item.pnumber", 1);
  6. //条件
  7. BasicDBObject cond = new BasicDBObject();
  8. //初始化
  9. BasicDBObject initial = new BasicDBObject();
  10. initial.append("total", 0);
  11. //reduce
  12. String reduce = "function Reduce(doc, out) { " +
  13. "  out.total+=doc.item.quantity;" +
  14. "}";
  15. SimpleDateFormat format=new SimpleDateFormat("yyyy-mm-dd");
  16. BasicDBList groupList=(BasicDBList) mongoTemplate.getCollection(collectionName).group(key, cond, initial, reduce);
  17. if(groupList!=null&&groupList.size()>0){
  18. System.out.println("date  item.pnumber  total");
  19. for(int i=0;i<groupList.size();i++){
  20. BasicDBObject obj=(BasicDBObject) groupList.get(i);
  21. System.out.println(format.format(obj.getDate("date"))+"  "+obj.getString("item.pnumber")+"  "+obj.getInt("total"));
  22. }
  23. }
  24. }

结果:

   

 

   2)实现一天卖出了多少个产品,金额是多少,平均价格是多少

  1. @Override
  2. public void getGroupAvg(String collectionName) {
  3. BasicDBObject key = new BasicDBObject();
  4. key.put("date", 1);
  5. //条件
  6. BasicDBObject cond = new BasicDBObject();
  7. //初始化
  8. BasicDBObject initial = new BasicDBObject();
  9. initial.append("total", 0);
  10. initial.append("money", 0.0);
  11. //reduce
  12. String reduce = "function Reduce(doc, out) { " +
  13. "  out.total+=doc.item.quantity;" +
  14. "   out.money+=doc.item.quantity*doc.item.price;" +
  15. "}";
  16. String finalize="function Finalize (out) { " +
  17. "  out.avg=out.money/out.total;" +
  18. "   return out;" +
  19. "}";
  20. SimpleDateFormat format=new SimpleDateFormat("yyyy-mm-dd");
  21. BasicDBList groupList=(BasicDBList) mongoTemplate.getCollection(collectionName).group(key, cond, initial, reduce, finalize);
  22. if(groupList!=null&&groupList.size()>0){
  23. System.out.println("date  total  money  avg");
  24. for(int i=0;i<groupList.size();i++){
  25. BasicDBObject obj=(BasicDBObject) groupList.get(i);
  26. System.out.println(format.format(obj.getDate("date"))+"  "+obj.getInt("total")+"  "+obj.getInt("money")+"  "+obj.getDouble("avg"));
  27. }
  28. }
  29. }

结果:

   

MongoDB 聚合Group(一)的更多相关文章

  1. mongodb MongoDB 聚合 group

    MongoDB 聚合 MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果.有点类似sql语句中的 count(*). 基本语法为:db.col ...

  2. mongodb MongoDB 聚合 group(转)

    MongoDB 聚合 MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果.有点类似sql语句中的 count(*). 基本语法为:db.col ...

  3. mongodb聚合 group

    MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果.有点类似sql语句中的 count(*). 基本语法为:db.collection.agg ...

  4. MongoDB 聚合管道(Aggregation Pipeline)

    管道概念 POSIX多线程的使用方式中, 有一种很重要的方式-----流水线(亦称为"管道")方式,"数据元素"流串行地被一组线程按顺序执行.它的使用架构可参考 ...

  5. Mongodb学习笔记四(Mongodb聚合函数)

    第四章 Mongodb聚合函数 插入 测试数据 ;j<;j++){ for(var i=1;i<3;i++){ var person={ Name:"jack"+i, ...

  6. 浅析mongodb中group分组

    这篇文章主要介绍了浅析mongodb中group分组的实现方法及示例,非常的简单实用,有需要的小伙伴可以参考下. group做的聚合有些复杂.先选定分组所依据的键,此后MongoDB就会将集合依据选定 ...

  7. MongoDB 聚合

    聚合操作过程中的数据记录和计算结果返回.聚合操作分组值从多个文档,并可以执行各种操作,分组数据返回单个结果.在SQL COUNT(*)和group by 相当于MongoDB的聚集. aggregat ...

  8. MongoDB聚合

    --------------------MongoDB聚合-------------------- 1.aggregate():     1.概念:         1.简介             ...

  9. MongoDB 聚合分组取第一条记录的案例及实现

    关键字:MongoDB: aggregate:forEach 今天开发同学向我们提了一个紧急的需求,从集合mt_resources_access_log中,根据字段refererDomain分组,取分 ...

随机推荐

  1. 服务器tomcat配置教程

    2018年上学期期末课程设计做了一个留言板,但是我需要把这个Jave Web弄到我的服务器上 首先我们可以安装jdk tomcat在启动时,会读取环境变量的信息,需要一个CATALINA_HOME 与 ...

  2. 第二阶段团队冲刺-three

    昨天: 修复博客作业查询功能. 今天: 绘制logo. 遇到的问题: 无.

  3. 团队冲刺Alpha(六)

    目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:翟丹丹 组员7:何家伟 组员8:政演 组员9:黄鸿杰 组员10:刘一好 组员11:何宇恒 展示 ...

  4. ocrosoft Contest1316 - 信奥编程之路~~~~~第三关 问题 P: 【数组】1234方阵(phalanx)

    http://acm.ocrosoft.com/problem.php?cid=1316&pid=15 题目描述 编程打印如下规律的n*n方阵.输入n,按规律输出方阵. 方阵规律如下图:使左对 ...

  5. nagios原理及配置详解

    1.Nagios如何监控Linux机器 NRPE总共由两部分组成:(1).check_nrpe插件,运行在监控主机上.服务器端安装详见:(2).NRPE daemon,运行在远程的linux主机上(通 ...

  6. JS计算器(自制)

    <!doctype html><html><header><meta charset="utf-8"><script src= ...

  7. Linux命令 -磁盘和文件系统类

    声明:本文所涉及到的Linux命令均为最常见的用法,未列举之参数,自行查阅man 1.df 磁盘容量 -h 以人类易读方式展示(GB.KB)等 df -h /usr 2.du 文件或目录的容量 -s ...

  8. BZOJ 4326 NOIP2015 运输计划(树上差分+LCA+二分答案)

    4326: NOIP2015 运输计划 Time Limit: 30 Sec  Memory Limit: 128 MB Submit: 1388  Solved: 860 [Submit][Stat ...

  9. ACM-The Coco-Cola Store

    题目: Once upon a time, there is a special coco-cola store. If you return three empty bottles to the s ...

  10. HDU 5690 矩阵快速幂

    All X Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submi ...