On this page
group
On this page
Definition
group-
Deprecated since version 3.4: Mongodb 3.4 deprecates the
groupcommand. Usedb.collection.aggregate()with the$groupstage ordb.collection.mapReduce()instead.Note
Because
groupuses JavaScript, it is subject to a number of performance limitations. For most cases the$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.The
groupcommand takes the following prototype form:{ group: { ns: <namespace>, key: <key>, $reduce: <reduce function>, $keyf: <key function>, cond: <query>, finalize: <finalize function> } }The command accepts a document with the following fields:
Field Type Description nsstring The collection from which to perform the group by operation. keydocument The field or fields to group. Returns a “key object” for use as the grouping key. $reducefunction 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. initialdocument Initializes the aggregation result document. $keyffunction Optional. Alternative to the keyfield. Specifies a function that creates a “key object” for use as the grouping key. Use$keyfinstead ofkeyto group by calculated fields rather than existing document fields.conddocument Optional. The selection criteria to determine which documents in the collection to process. If you omit the condfield,groupprocesses all the documents in the collection for the group operation.finalizefunction 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$keyfand$reducefields that also specify a function, this field name isfinalize, not$finalize.For the shell, MongoDB provides a wrapper method
db.collection.group(). However, thedb.collection.group()method takes thekeyffield and thereducefield whereas thegroupcommand takes the$keyffield and the$reducefield.
Behavior
Limits and Restrictions
The group command does not work with sharded clusters. Use the aggregation framework or map-reduce in sharded environments.
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.
Prior to 2.4, the group command took the mongod instance’s JavaScript lock which blocked all other JavaScript execution.
mongo Shell JavaScript Functions/Properties
map-reduce operations, the group command, and $where operator expressions cannot access certain global functions or properties, such as db, that are available in the mongo shell.
The following JavaScript functions and properties are available to map-reduce operations, the group command, and $where operator expressions:
| Available Properties | Available Functions | |
|---|---|---|
args
MaxKey
MinKey
|
assert()
BinData()
DBPointer()
DBRef()
doassert()
emit()
gc()
HexData()
hex_md5()
isNumber()
isObject()
ISODate()
isString()
|
Map()
MD5()
NumberInt()
NumberLong()
ObjectId()
print()
printjson()
printjsononeline()
sleep()
Timestamp()
tojson()
tojsononeline()
tojsonObject()
UUID()
version()
|
JavaScript in MongoDB
Although group uses JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application.
Examples
The following are examples of the db.collection.group() method. The examples assume an orders collection with documents of the following prototype:
{
_id: ObjectId("5085a95c8fada716c89d0021"),
ord_dt: ISODate("2012-07-01T04:00:00Z"),
ship_dt: ISODate("2012-07-02T04:00:00Z"),
item:
{
sku: "abc123",
price: 1.99,
uom: "pcs",
qty: 25
}
}
Group by Two Fields
The following example groups by the ord_dt and item.sku fields those documents that have ord_dt greater than 01/01/2012:
db.runCommand(
{
group:
{
ns: 'orders',
key: { ord_dt: 1, 'item.sku': 1 },
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
$reduce: function ( curr, result ) { },
initial: { }
}
}
)
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:
{ "retval" :
[ { "ord_dt" : ISODate("2012-07-01T04:00:00Z"), "item.sku" : "abc123"},
{ "ord_dt" : ISODate("2012-07-01T04:00:00Z"), "item.sku" : "abc456"},
{ "ord_dt" : ISODate("2012-07-01T04:00:00Z"), "item.sku" : "bcd123"},
{ "ord_dt" : ISODate("2012-07-01T04:00:00Z"), "item.sku" : "efg456"},
{ "ord_dt" : ISODate("2012-06-01T04:00:00Z"), "item.sku" : "abc123"},
{ "ord_dt" : ISODate("2012-06-01T04:00:00Z"), "item.sku" : "efg456"},
{ "ord_dt" : ISODate("2012-06-01T04:00:00Z"), "item.sku" : "ijk123"},
{ "ord_dt" : ISODate("2012-05-01T04:00:00Z"), "item.sku" : "abc123"},
{ "ord_dt" : ISODate("2012-05-01T04:00:00Z"), "item.sku" : "abc456"},
{ "ord_dt" : ISODate("2012-06-08T04:00:00Z"), "item.sku" : "abc123"},
{ "ord_dt" : ISODate("2012-06-08T04:00:00Z"), "item.sku" : "abc456"}
],
"count" : 13,
"keys" : 11,
"ok" : 1 }
The method call is analogous to the SQL statement:
SELECT ord_dt, item_sku
FROM orders
WHERE ord_dt > '01/01/2012'
GROUP BY ord_dt, item_sku
Calculate the Sum
The following example groups by the ord_dt and item.sku fields those documents that have ord_dt greater than 01/01/2012 and calculates the sum of the qty field for each grouping:
db.runCommand(
{ group:
{
ns: 'orders',
key: { ord_dt: 1, 'item.sku': 1 },
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
$reduce: function ( curr, result ) {
result.total += curr.