Skip to main content

$lookup

The $lookup stage in MongoDB performs a left outer join to another collection in the same database to filter in documents from the "joined" collection for processing. It's part of MongoDB's aggregation framework and allows you to combine documents from different collections based on a related field between them.

Basic Syntax

The basic syntax of a $lookup operation is as follows:

db.orders.aggregate([
{
$lookup: {
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
]);

In this example, the $lookup stage performs a join between the orders collection and the inventory collection based on the item field from orders and the sku field from inventory. The resulting documents will have a new array field called inventory_docs that contains the matching documents from the inventory collection.

Parameters

  • from: The collection to join with.
  • localField: The field from the documents input to the $lookup stage.
  • foreignField: The field from the documents in the from collection.
  • as: The output array field that contains the matching documents from the from collection.

Advanced $lookup

MongoDB also supports a more advanced form of $lookup that allows for specifying additional pipeline stages to run on the joined collection. This enables more complex queries and transformations.

db.orders.aggregate([
{
$lookup: {
from: "inventory",
let: { order_item: "$item" },
pipeline: [
{ $match: { $expr: { $eq: ["$sku", "$$order_item"] } } },
{ $project: { stock: 1, _id: 0 } }
],
as: "inventory_docs"
}
}
]);

In this example, the let option defines variables that can be accessed within the pipeline option. The pipeline option specifies additional aggregation pipeline stages to apply to the documents from the from collection.

Considerations

  1. Performance: $lookup can be resource-intensive, especially when dealing with large collections. Proper indexing can mitigate this.
  2. Data Consistency: Since $lookup performs a left outer join, if there are no matching documents in the from collection, the as field will be an empty array.
  3. Nested Arrays: If the foreignField contains an array of values, $lookup performs the join for each element of the array.