13. Advanced $lookup with a Foreign Pipeline

The pipeline form of $lookup allows filtering and reshaping foreign documents. let passes values from the current document into the foreign pipeline. Reference these variables using $$name; use $expr when a $match compares expressions or variables.

Use $match, $project, $sort, and $limit inside the foreign pipeline as appropriate. Correlated lookups can be powerful but should be tested with representative data. Index eligibility depends on the expression and query shape.

Code Example
db.orders.aggregate([
  {
    $lookup: {
      from: "customers",
      let: { orderCustomerId: "$customerId" },
      pipeline: [
        { $match: { $expr: { $eq: ["$_id", "$$orderCustomerId"] } } },
        { $project: { name: 1, city: 1, tier: 1 } },
        { $limit: 1 }
      ],
      as: "customer"
    }
  }
]);
Key Takeaways
  • A lookup pipeline can filter foreign documents.
  • Use let to pass source values.
  • Use $$variable to reference lookup variables.
  • Verify performance with actual plans.
Knowledge Check

How do you reference a variable declared in $lookup's let option?