mongoDB中的group

mongodb 是一种NoSQL 数据,怎样能够实现关系数据库中的group功能?

Group

Note: currently one must use map/reduce instead of group() in sharded MongoDB configurations.

group returns an array of grouped items. The command is similar to SQL's group by. The SQL statement

select a,b,sum(c) csum from coll where active=1 group by a,b

corresponds to the following in MongoDB:

db.coll.group(
           {key: { a:true, b:true },
            cond: { active:1 },
            reduce: function(obj,prev) { prev.csum += obj.c; },
            initial: { csum: 0 }
            });

Note: the result is returned as a single BSON object and for this reason must be fairly small – less than 10,000 keys, else you will get an exception. For larger grouping operations without limits, please use map/reduce .

group takes a single object parameter containing the following fields:

  • key: Fields to group by.
  • reduce: The reduce function aggregates (reduces) the objects iterated. Typical operations of a reduce function include summing and counting. reduce takes two arguments: the current document being iterated over and the aggregation counter object. In the example above, these arguments are named obj and prev.
  • initial: initial value of the aggregation counter object.
  • keyf: An optional function returning a "key object" to be used as the grouping key. Use this instead of key to specify a key that is not a single/multiple existing fields. Could be used to group by day of the week, for example. Set in lieu of key.
  • cond: An optional condition that must be true for a row to be considered. This is essentially a find() query expression object. If null, the reduce function will run against all rows in the collection.
  • finalize: An optional function to be run on each item in the result set just before the item is returned. Can either modify the item (e.g., add an average field given a count and a total) or return a replacement object (returning a new object with just _id and average fields). See jstests/group3.js for examples.

下面是我使用mongoVue工具实现group 



这里可以输入key,也就是你所想group 的字段,如果没有给个{}就可以。
Conditions 是条件筛选。status=30


Initial Value 就是你自己定义累计器初始值,每个分组第一次调用reduce方法的时候传递给它的值,在一个分组里边,始终使用同一个累计器,对累计器的修改会被保持下来。


Finalize 

使用终结器(Finalizer)

终结器用于最小化从数据库到用户的数据,我们看一个博客的例子,每篇博客都有几个标签,我们想找出每天最流行的标签是什么。那么我们按照日期进行分组,对每个标签计数:

JAVA FOR MONGODB:

http://stackoverflow.com/questions/6013645/how-do-i-pass-parameters-to-mongodb-map-reduce-in-java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值