$lookup — Joining Collections
12 min read
Joining with $lookup
$lookup performs a left outer join between the current collection and another collection in the same database. It is the aggregation equivalent of SQL JOIN.
Suppose we have a courses collection and each student document holds a courseId that references a course. We can enrich the student documents with full course details using $lookup.
js
// courses collection
db.courses.insertMany([
{ _id: "fs101", title: "Full Stack", duration: 12 },
{ _id: "ds201", title: "Data Science", duration: 10 }
]);
// students reference a courseId
db.students.updateOne(
{ name: "Riya Sharma" },
{ $set: { courseId: "fs101" } }
);
// Join students with courses
db.students.aggregate([
{
$lookup: {
from: "courses",
localField: "courseId",
foreignField: "_id",
as: "courseDetails"
}
},
{ $unwind: { path: "$courseDetails", preserveNullAndEmptyArrays: true } },
{
$project: {
name: 1,
"courseDetails.title": 1,
"courseDetails.duration": 1
}
}
]);$lookup always produces an array in the as field (even for a single match). Use $unwind after the lookup to flatten it into a single subdocument.
Ready to test yourself?
Practice MongoDB— quiz & coding exercises