Here is an example from MongoDB tutorial (here it collection ZIP Code db:
db.zipcodes.aggregate( [
{ $group: { _id: \"$state\", totalPop: { $sum: \"$pop\"
The _id
field is mandatory, but you can set it to null
if you do not wish to aggregate with respect to a key, or keys. Not utilising it would result in a single aggregate value over the fields. It is thus acting a 'reserved word' in this context, indicating what the resulting 'identifier'/key is for each group.
In your case, grouping by _id: "$state"
would result in n
aggregate results of totalPop
, provided there there are n
distinct values for state
(akin to SELECT SUM() FROM table GROUP BY state
). Whereas,
$group : {_id : null, totalPop: { $sum: "$pop" }}}
would provide a single result for totalPop
(akin to SELECT SUM() FROM table
).
This behaviour is well described in the group operator documentation.