$group

The $group stage operator allows you to aggregate on a specific field. You can then apply accumulator operators (https://docs.mongodb.com/manual/reference/operator/aggregation/group/#accumulator-operator) to the result in order to produce sums, averages, and so on. Here is an example query which produces totals by customer name, including the average quantity and the total number of purchases. Note that the _id field represents the grouping criteria. The other field names (total, avgQty, and count) are arbitrarily chosen:

Get MongoDB 4 Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.