0PricingLogin
MongoDB Academy · Lesson

$lookup: Joining Collections in the Pipeline

Learners will perform left outer joins between collections using $lookup and understand the performance implications of cross-collection joins.

Why $lookup Exists

MongoDB is designed around embedding related data, but sometimes data must live in separate collections—especially in many-to-many or one-to-many scenarios where embedding would cause unbounded document growth. The $lookup stage performs a left outer join between the current collection (the 'left' side) and another collection (the 'right' side), allowing you to bring related data together server-side in a single aggregation pipeline.

Basic $lookup Syntax

The basic $lookup has four required fields: from (the collection to join), localField (field in the input document), foreignField (field in the joined collection), and as (name of the array field added to the output). The result is an array because one document might match multiple documents in the joined collection.

// Join orders with their product details
db.orders.aggregate([
  { $lookup: {
    from: 'products',          // collection to join
    localField: 'productId',   // field in orders
    foreignField: '_id',       // field in products
    as: 'productDetails'       // output array field name
  }}
]);
// Each order now has a 'productDetails' array with matching products

All lessons in this course

  1. $lookup: Joining Collections in the Pipeline
  2. $unwind: Deconstructing Array Fields
  3. $addFields, $replaceRoot, and $mergeObjects
  4. $out and $merge: Writing Pipeline Results
← Back to MongoDB Academy