MongoDB - objects? Why do I need _id in aggregate

后端 未结 3 1224
悲&欢浪女
悲&欢浪女 2021-01-02 03:47

Here is an example from MongoDB tutorial (here it collection ZIP Code db:

db.zipcodes.aggregate( [
   { $group: { _id: \"$state\", totalPop: { $sum: \"$pop\"         


        
3条回答
  •  無奈伤痛
    2021-01-02 04:09

    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.

提交回复
热议问题