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
$lookupstage. - 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"
}
}
]);