💖 $lookup stage:
In the MongoDB aggregation framework, the $lookup stage is used to combine multiple collections based on the common fields of the document and include the related data in the output document.
💢 Syntax:
{ $lookup: { from: <foreignCollection>, localField: <localField>, foreignField: <foreignField>, as: <outputArrayField> } }
from:
The name of the foreign collection you want to join with.
localField:
The field from the input documents that will be used to match with the foreignField
in the foreign collection.
foreignFiel:
The field from the foreign collection that will be used to match with the localField
in the input documents.
as:
The name of the new array field that will hold the joined documents from the foreign collection.
💧 Combine or join multiple collections:
db.orders.aggregate([ { $lookup: { from: "products", localField: "productId", foreignField: "_id", as: "productDetails" } }, { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customerDetails" } } ])
Post a Comment