MongoDB Aggregation $lookup
Aggregation $lookup
This aggregation stage performs a left outer join to a collection in the same database.
There are four required fields:
from
: The collection to use for lookup in the same databaselocalField
: The field in the primary collection that can be used as a unique identifier in thefrom
collection.foreignField
: The field in thefrom
collection that can be used as a unique identifier in the primary collection.as
: The name of the new field that will contain the matching documents from thefrom
collection.
Example
In this example, we are using the "sample_mflix" database loaded from our sample data in the Intro to Aggregations section.
db.comments.aggregate([
{
$lookup: {
from: "movies",
localField: "movie_id",
foreignField: "_id",
as: "movie_details",
},
},
{
$limit: 1
}
])
Try it Yourself »
This will return the movie data along with each comment.