Multi-Table Joins with $lookup & Array Flattening with $unwind
Multi-Table Joins with $lookup & Array Flattening with $unwind
Real-world reporting requires combining documents from disparate collections and manipulating nested arrays. The $lookup stage performs true server-side left outer joins between collections, and the $unwind stage deconstructs array fields into individual stream documents.
1. Multi-Collection Joins: The $lookup Stage
The $lookup stage performs a left outer join to an unsharded collection in the same database:
Basic Syntax:
Note: $lookup always outputs an array in the as field, even if only one matching document is found.
2. Array Flattening: The $unwind Stage
Arrays often contain multiple elements that need to be analyzed individually. The $unwind stage deconstructs an array field from the input documents to output a document for each element in the array:
3. Combining $lookup, $unwind, and $group
Find the most popular course tags across all enrollments:
Multiple Choice Questions
$lookup aggregation stage perform?$lookup stage assign to the output field designated by as?$unwind stage do when applied to an array with 4 elements?$unwind if a document has an empty array [] or the field is missing/null?foreignField in a joined $lookup collection be indexed?Database Indexing Strategies (Single, Compound, TTL) & Query Optimization
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.