Group and total
This next section provides an example of the most commonly used pattern for grouping and summarizing data from a collection.
Scenario
You need to generate a report to show what each shop customer purchased in 2020. You will group the individual order records by customer, capturing each customer's first purchase date, the number of orders they made, the total value of all their orders, and a list of their order items sorted by date.
Populating the sample data
To start with, drop any old version of the database (if it exists) and then populate a new orders
collection with nine order documents spanning 2019-2021, for three different unique customers. Each order record will contain a customer ID, the date of the order, and the dollar total for the order:
db = db.getSiblingDB("book-group-and-total"); db.dropDatabase(); // Create index for an orders collection db.orders.createIndex({"orderdate": -1}); // Insert records into the orders...