Aggregation pipeline expression operator examples

In this first example, we are going to generate a query to satisfy a management request for a report on buying patterns based on the day of the week. We are using the $bucket stage operator to produce seven arrays of purchases representing each day of the week. We will then group by $dayOfWeek, which in turn uses $toDate to produce a BSON Date instance. The $push will be used to copy the arrays out into the pipeline. We will then use the $project stage to produce the output, which consists of the day's number, the day's abbreviation, and the sum. In order to get the actual three-letter day abbreviation, we use the $arrayElemAt operator against the array days.

Note the use of $subtract to ...

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.