How to Join Collections in MongoDB Using $lookup Aggregation?

Asked 17 hours ago Updated 17 hours ago 33 views

0

Coming from a relational database background, I need to query related documents stored in separate collections. How does the $lookup operator work in MongoDB's aggregation pipeline to join two collections?

Understanding $lookup

The $lookup stage performs a left outer join to an unsharded collection in the same database, filtering in documents from the joined collection for processing.

  • localField: The field from the input documents passed into the $lookup stage.
  • foreignField: The field from the documents in the target collection.
  • as: The name of the new array field added to input documents containing matches.

Example Aggregation Pipeline

db.orders.aggregate([
    {
        $lookup: {
            from: "products",
            localField: "productId",
            foreignField: "_id",
            as: "productDetails"
        }
    }
]);

0 Answers


Write Your Answer