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.
使用终结器(Finalizer)
终结器用于最小化从数据库到用户的数据,我们看一个博客的例子,每篇博客都有几个标签,我们想找出每天最流行的标签是什么。那么我们按照日期进行分组,对每个标签计数:
JAVA FOR MONGODB:
http://stackoverflow.com/questions/6013645/how-do-i-pass-parameters-to-mongodb-map-reduce-in-java