Combining Collections
This guide demonstrates how to merge data from two collections using MongoDB's aggregation framework.
Use Case
You need to combine related data from separate collections - in this case, retrieving listings along with their associated reviews.
Prerequisites
This guide uses the collections we created in the previous guide where we split the listingsAndReviews
collection into separate listings
and reviews
collections.
Using $lookup
The $lookup
operation performs a left outer join, allowing you to incorporate documents from one collection into matching documents from another.
Result Structure
After execution, each document from the listings
collection will contain a new reviews
array field with all matching review documents.
Additional Options
For more control over joined data:
- Use pipeline.project()
after lookup to shape the output
- Add matching conditions with let
and pipeline
parameters
- Explore the $unwind
stage to process array results