Relational Modeling with $lookup

Relational Modeling with $lookup in NoSQL Databases: While embedding data is the default NoSQL philosophy, relational connections are sometimes necessary to…

While embedding data is the default NoSQL philosophy, relational connections are sometimes necessary to prevent unbounded document growth. MongoDB provides the $lookup stage within its Aggregation Pipeline to perform left outer joins between collections.


1. Basic Foreign Key $lookup

Suppose we have an orders collection where each document stores a customer_id referencing a document in the users collection:

// Orders collection:
// { _id: 101, customer_id: 501, total: 120.00 }

// Users collection:
// { _id: 501, name: "David Chen", tier: "Gold" }

db.orders.aggregate([
  {
    $match: { total: { $gte: 100 } }
  },
  {
    $lookup: {
      from: "users",             // Foreign collection to join
      localField: "customer_id", // Field in 'orders'
      foreignField: "_id",       // Field in 'users'
      as: "customer_info"        // Output array field name
    }
  },
  {
    // $unwind converts the single-element array into a flat subdocument
    $unwind: "$customer_info"
  },
  {
    $project: {
      order_id: "$_id",
      total: 1,
      customer_name: "$customer_info.name",
      customer_tier: "$customer_info.tier"
    }
  }
]);

2. Uncorrelated Subqueries with $lookup Pipeline

You can specify a custom pipeline inside $lookup to filter, sort, and limit joined rows before they are returned into memory:

db.authors.aggregate([
  {
    $lookup: {
      from: "books",
      let: { authorId: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: ["$author_id", "$$authorId"] },
                { $eq: ["$published", true] }
              ]
            }
          }
        },
        { $sort: { publication_year: -1 } },
        { $limit: 3 } // Fetch only the top 3 most recent books!
      ],
      as: "recent_books"
    }
  }
]);

Performance Rule: Every $lookup requires scanning the foreign collection. Ensure the foreignField has an active index, or query latency will degrade exponentially under scale!