$bucket

This stage operator allows you to break up the output into a set of distinct arrays called buckets. The criteria used to separate documents into buckets is determined by the field identified with the groupBy parameter. This parameter matches the document field against the limits specified by the boundaries parameter. The values in boundaries can be either numeric or strings.

In the following example, we break up the query into buckets based on name. The boundary [ "A", "G", "M", "S", "Y" ] means that multiple buckets will be formed based on customer names A-F, G-L, M-R, and S-X. The Y and Z will fall into the "default." We then use the $project stage to produce a sum of the amounts for this group of customers:

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.