MongoDB’s $lookup Aggregator

More than a pair of

Start by creating a table ‘countryCode’

db.countryCode.insert([{code: 1}, {code: 20}, {code: 30}])
Copy the code

The second table, ‘countryCodeLookup’, shows the relationship between the country code and the country name

db.countryCodeLookup.insert([{code: 1, name: "United States"}, {code: 20, name: "Egypt"}, 
{code: 1, name: "Foobar"}, {code: 30, name: "Greece"}])
Copy the code

Let’s join the two collections using the $lookup operator, where $project filters the properties

db.countryCode.aggregate([
{ $lookup: {from: "countryCodeLookup", localField: "code", foreignField: "code", as: "countryName"} },
{ $project: {"code":1, "countryName.name":1, "_id":0} }
])
Copy the code

$match will query the joined table and display those that match the conditions.

db.countryCode.aggregate([ { $lookup: {from: "countryCodeLookup", localField: "code", foreignField: "code", as: "CountryName"}}, {$project: {" code ": 1," countryName. The name ": 1," _id ": 0}}, {$match: {" code" : 1.0}}])Copy the code

One to one

The $unwind operator breaks up the AS array in $lookup and flattens it back.

db.countryCode.aggregate([ { $lookup: {from: "countryCodeLookup", localField: "code", foreignField: "code", as: "countryName"} }, { $project: {"code":1, "countryName.name":1, "_id":0} }, { $unwind: "$countryName"}, {$match: {" code ": 1.0}}])Copy the code

Now countryName is a subdocument, set it in project and pull out the property in the subdocument, so $project is going to come after the $unwind property.

db.countryCode.aggregate([
{ $lookup: {from: "countryCodeLookup", localField: "code", foreignField: "code", as: "countryName"} },
{ $unwind: "$countryName"},
{ $project: {"code":1, "name": "$countryName.name", "_id":0} }
])
Copy the code