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