MongoDB Aggregation $lookup
Introduction
The $lookup
stage in MongoDB's aggregation framework is used to perform left outer joins between two collections. This allows you to combine documents from different collections based on a shared field, enabling you to retrieve related data in a single query.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
and two populated collections with sample data.
Step 1: Start mongosh
mongosh
Open Terminal/Command Prompt:
Launch your terminal (macOS/Linux) or command prompt (Windows).
Start
mongosh
:Type the following command and press Enter:
Step 2: Switch to the Database
Switch to the database where your collections are located.
Use a Database:
Step 3: Sample Data
Assume you have two collections, sales
and products
. The sales
collection has documents that look like this:
sales collection:
The products
collection has documents that look like this:
products collection:
Step 4: Using $lookup
$lookup
1. Basic Usage of $lookup
$lookup
To perform a left outer join and combine documents from the sales
collection with those from the products
collection based on the item_id
field in sales
and the _id
field in products
, use the following query:
Output:
2. Unwinding the Joined Results
If you want to flatten the results so that each product detail is represented as a separate document, you can use the $unwind
stage after $lookup
:
Output:
3. Handling Cases with No Matches
If there are documents in the sales
collection that do not have a matching document in the products
collection, the productDetails
field will still be included, but it will be an empty array. You can use $unwind
with the preserveNullAndEmptyArrays
option to keep these documents in the output:
4. Combining with Other Stages
You can combine $lookup
with other stages for complex aggregations. For example, to calculate the total revenue for each sale, you can include a $project
stage:
Output:
Conclusion
You have learned how to use the $lookup
stage in MongoDB's aggregation framework to perform left outer joins between collections. This stage is powerful for combining related data from multiple collections, allowing you to enrich your documents and perform more complex queries.
Feel free to reach out if you have any questions or need further guidance!
Last updated