$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- $lookupstage.
- foreignField: The field from the documents in the- fromcollection.
- as: The output array field that contains the matching documents from the- fromcollection.
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
- Performance: $lookupcan be resource-intensive, especially when dealing with large collections. Proper indexing can mitigate this.
- Data Consistency: Since $lookupperforms a left outer join, if there are no matching documents in thefromcollection, theasfield will be an empty array.
- Nested Arrays: If the foreignFieldcontains an array of values,$lookupperforms the join for each element of the array.