$lookup: Joining Collections
Sometimes the data you need is in another collection. This course has a directors collection with each director's country:
db.directors.find()
Output:
[
{ _id: 'Christopher Nolan', country: 'UK' },
{ _id: 'Bong Joon-ho', country: 'South Korea' },
{ _id: 'Damien Chazelle', country: 'USA' }
]
$lookup is the aggregation stage that joins two collections. It adds the matching documents from the other collection to each document:
db.movies.aggregate([
{ $lookup: {
from: "directors",
localField: "director",
foreignField: "_id",
as: "info"
} },
{ $project: { _id: 0, title: 1, "info.country": 1 } },
{ $sort: { title: 1 } },
{ $limit: 3 }
])
Output:
[
{ title: 'Dunkirk', info: [ { country: 'UK' } ] },
{ title: 'First Man', info: [ { country: 'USA' } ] },
{ title: 'Inception', info: [ { country: 'UK' } ] }
]
The $lookup stage has four parts:
fromis the other collection,directors.localFieldis the field in this collection, the movie'sdirector.foreignFieldis the field in the other collection, the director's_id.asis the name of the new field that holds the matches.
The new field is always an array, because many documents could match. Here each movie has one director, so each array has one document. If nothing matches, the movie is still in the result, with an empty array info: []. If you are sure there is exactly one match, $unwind can turn the array into a single document.
In the exercise, go the other way: start from the directors and look up their movies.