Multi-field join and one-to-many
The previous example illustrated how to solve a one-to-one join. However, you may need to perform a one-to-many join, where a document in the first collection maps to potentially many records in the second collection. Here, you will learn how to achieve this in a pipeline.
Scenario
You want to generate a report to list all the orders made for each product in 2020. To achieve this, you need to take a shop's products collection and join each product record to all its orders stored in an orders collection. There is a one-to-many relationship between both collections, based on a match of two fields on each side. Rather than joining on a single field such as product_id
(which doesn't exist in this dataset), you need to use two common fields to join (product_name
and product_variation
).
Note
The requirement to perform a one-to-many join does not mandate the need to join the two collections by multiple fields on each side. However, in...