Search⌘ K
AI Features

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.

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 an ObjectId paired with a ref to another model. This course is referenced by the string id (orders.userId holds "0001"), so $lookup is the technique that works against the seeded collections. populate() is covered as an alternative where ObjectId references are used.

To make the relationship concrete, the next visual should show orders being ...