Solution: Grouping Across Collections
The aggregation pipeline for the orders collection begins with filtering documents using $match to include only orders from January 1, 2025, onward. It then uses $unwind to separate items into individual documents, followed by $lookup to join product details from the products collection. The $project stage shapes the output, selecting relevant fields and calculating revenue. Finally, $group aggregates data by productId to sum quantities and revenue, and $sort orders the results by revenue in descending order. Key concepts include filtering, unwinding arrays, joining collections, projecting fields, aggregating data, and sorting results.
We'll cover the following...
The explanation of the query is given below:
Line 1: This begins an aggregation pipeline on the
orderscollection.Lines 4–7:
$matchfilters documents before processing further. This keeps only orders placed on or after January 1, 2025. Whereas,$gtemeans “greater than or equal to.”Lines 10–12:
$unwindtakes an array field (items) and creates a separate document for each element. If ...