$groupoperator in the aggregation pipeline provides a suitable alternative with fewer restrictions.
Groups documents in a collection by the specified key and performs simple aggregation functions, such as computing counts and sums. The command is analogous to a
SELECT <...> GROUP BYstatement in SQL. The command returns a document with the grouped records as well as the command meta-data.
groupcommand takes the following prototype form:
The command accepts a document with the following fields:
Field Type Description
string The collection from which to perform the group by operation.
document The field or fields to group. Returns a “key object” for use as the grouping key.
function An aggregation function that operates on the documents during the grouping operation. These functions may return a sum or a count. The function takes two arguments: the current document and an aggregation result document for that group.
document Initializes the aggregation result document.
function Optional. Alternative to the
keyfield. Specifies a function that creates a “key object” for use as the grouping key. Use
keyto group by calculated fields rather than existing document fields.
document Optional. The selection criteria to determine which documents in the collection to process. If you omit the
groupprocesses all the documents in the collection for the group operation.
function Optional. A function that runs each item in the result set before
groupreturns the final value. This function can either modify the result document or replace the result document as a whole. Unlike the
$reducefields that also specify a function, this field name is
For the shell, MongoDB provides a wrapper method
db.collection.group(). However, the
db.collection.group()method takes the
keyffield and the
reducefield whereas the
groupcommand takes the
$keyffield and the
The result set must fit within the maximum BSON document size.
Additionally, in version 2.2, the returned array can contain at most 20,000 elements; i.e. at most 20,000 unique groupings. For group by operations that results in more than 20,000 unique groupings, use
mapReduce. Previous versions had a limit of 10,000 elements.
|Available Properties||Available Functions|
The following are examples of the
db.collection.group() method. The examples assume an
orders collection with documents of the following prototype:
The following example groups by the
item.sku fields those documents that have
ord_dt greater than
The result is a document that contain the
retval field which contains the group by records, the
count field which contains the total number of documents grouped, the
keys field which contains the number of unique groupings (i.e. number of elements in the
retval), and the
ok field which contains the command status:
The method call is analogous to the SQL statement: