Lesson 8: SQL JOINs in MongoDB / Learn
Code Summary: SQL JOINs In MongoDB
In SQL, we use INNER JOIN in our statement to join two tables:
SELECT t.*, a.account_id, a.account_holder
FROM transfers t
INNER JOIN account_holder a ON t.transfer_id = a.transfers_complete
This SQL JOIN query does the following:
- Joins the records of the
transferstable with the records of theaccountstable. - Uses the
transfers_completefield from theaccountstable and thetransfer_idfield from thetransferstable. - Projects the
account_holderandaccount_idfields from theaccountstable into thetransferstable.
To do the same in MongoDB, we use the $lookup operator from the aggregation framework.
Inside the $lookup stage, we define the following:
accountsis the collection to join.transfer_idaslocalFieldis the field to use in the equality match from the input documents.transfers_completeasforeignFieldis the field to use in the equality match from thetransferscollection.account_idandaccount_holderare the projected fields in the resulting documents while suppressing the_idfield.account_holderis the name of the new array field to add to the input documents.
Here’s the code:
db.transfers.aggregate( [
{
$lookup:
{
from: "accounts",
localField: "transfer_id",
foreignField: "transfers_complete",
pipeline: [
{ $project: { _id: 0, account_id: 1, account_holder: 1 } }
],
as: "account_holder"
}
}] )