Mongodb Guide

$lookup Stage (Join) in MongoDB

1. Definition

The $lookup stage is used to perform a join between two collections in MongoDB. It allows you to combine data from multiple collections based on a common field.

2. Simple Understanding

👉 It works like JOIN in SQL
👉 It combines data from two collections into one result

3. When to Use

  • When using referenced data model
  • When data is stored in multiple collections
  • When you need combined data
  • When avoiding data duplication

4. Where it is Used

  • E-commerce (users + orders)
  • Blog systems (users + posts)
  • Social media apps
  • Backend APIs

5. Why We Use It

  • To combine related data
  • To simulate SQL joins
  • To fetch related documents in one query
  • To support normalized data model

6. How It Works

  • Matches fields from two collections
  • Creates a new array field with joined data
  • Uses localField and foreignField
  • Acts like a left outer join

7. Basic Syntax

db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "userDetails"
    }
  }
]);

8. Real Example

// Orders collection
{
  product: "Laptop",
  userId: "u1"
}

// Users collection
{
  _id: "u1",
  name: "Manaswini"
}

// Join using $lookup
db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "userInfo"
    }
  }
]);

9. Explanation

  • from → target collection
  • localField → field in current collection
  • foreignField → field in other collection
  • as → output array field

10. Advantages

  • Combines data from multiple collections
  • Supports normalized data model
  • Reduces multiple queries
  • Powerful for complex data fetching

11. Disadvantages

  • Can be slow for large datasets
  • Consumes more memory
  • Not as fast as embedded model

Interview Points

  • $lookup = JOIN in SQL
  • Used for combining collections
  • Acts like left outer join
  • Returns data as an array