Video Transcript (English)
One of the false narratives about MongoDB is that it doesn’t allow joining data. This could not be more inaccurate.
In this lesson, we’ll show you how to perform the equivalent of SQL joins by using MongoDB’s aggregation framework. We’ll also give examples of querying across different collections.
In SQL, a JOIN clause is used to combine rows from two or more tables, based on a related column between them.
MongoDB joins are performed by using the $lookup operator from the aggregation framework. This performs a left outer join to a collection in the same database to filter in documents from the "joined" collection for processing.
Before we see this in action, let’s explore the syntax of the $lookup stage: from specifies the collection in the same database to perform the join with. localField specifies the field in the documents from the collection that we’re working in that are input to the $lookup stage. foreignField specifies the field from the documents in the “from” collection, which is the collection that is joined. pipeline determines the resulting documents from the joined collection. And as specifies the name of the new array field to add to the input documents.
Let’s go through an example.
This SQL query does the following: It joins the records of the `transfers` table with the records of the `accounts` table. It uses the fields `transfers_complete` from the `accounts` table and `transfer_id` from the `transfers` table. It projects the `account_holder` and `account_id` fields from the `accounts` table into the `transfers` documents.
We can run this same query in MongoDB by creating a $lookup with an aggregation pipeline.
To start, we create an empty aggregation query that acts on the `transfers` collection.
Then, we add the $lookup stage.
Inside the $lookup stage, we define the following:`accounts` is the collection to join. `transfer_id` as `localField` is the field to use in the equality match from the input documents. ‘transfers_complete’ as ‘foreignField’ is the field to use in the equality match from the `transfers` collection. `account_id` and `account_holder` are the projected fields in the resulting documents while suppressing the `_id` field. `account_holder` is the name of the new array field to add to the input documents.
When we run this command, we’ll get output like this. Because the full output is very long, only a portion is shown here. It shows that the two tables have been joined successfully, and the `account_id` and `account_holder` fields have been projected into the transfer documents.
There are a couple of things to remember about using $lookup: First, the pipeline cannot include the $out or $merge stages. And, it’s generally not recommended to build your data around multiple joins, though doing so can be useful in some situations such as analytics. Amazing! You’ve learned how to perform a SQL join in MongoDB by using the $lookup operator from the aggregation framework.