One-to-Many Relationships with $lookup
Explore how to model one-to-many relationships in MongoDB using the aggregation $lookup stage. Understand string-based references between collections, use $unwind and $project to shape joined data, and learn when to apply these joins efficiently for MERN stack applications.
We'll cover the following...
The previous lesson established when to reference instead of embed. This lesson shows how to follow a reference in this course’s data. A user has many orders, and each order points back to its user through orders.userId, the classic one-to-many shape. Because the dataset references by the string field id rather than a MongoDB ObjectId, the join is done with an aggregation $lookup, which matches any field to any field.
Note: Mongoose’s
populate()is the other common way to follow a reference, but it requires the reference to be anObjectIdpaired with arefto another model. This course is referenced by the stringid(orders.userIdholds"0001"), so$lookupis the technique that works against the seeded collections.populate()is covered as an alternative whereObjectIdreferences are used.
To make the relationship concrete, the next visual should show orders being ...