MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Multi-Table Joins with $lookup & Array Flattening with $unwind0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
4.1One-to-Few (Embedded) vs One-to-Many (Referenced) Data Modeling4.2Query Population with .populate() & Multi-Level Population4.3Aggregation Pipeline Architecture: $match, $group, $project & $sort4.4Multi-Table Joins with $lookup & Array Flattening with $unwind4.5Database Indexing Strategies (Single, Compound, TTL) & Query Optimization
HomeTutorialsMongoDB & MongooseMulti-Table Joins with $lookup & Array Flattening with $unwind
Database Indexing Strategies (Single, Compound, TTL) & Query Optimization

Multi-Table Joins with $lookup & Array Flattening with $unwind

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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:

1Orders Collection ---> [$lookup from "users"] ---> Orders with embedded User details

Basic Syntax:

1const orderDetails = await db.collection('orders').aggregate([
2 {
3 $lookup: {
4 from: 'users', // Target collection to join
5 localField: 'customerId', // Field from the input documents ('orders')
6 foreignField: '_id', // Field from documents of the 'from' collection ('users')
7 as: 'customerDetails' // Output array field name
8 }
9 }
10]).toArray();

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:

1Input Document:
2{ _id: 1, item: "Course Bundle", tags: ["react", "node", "mongo"] }
3 
4After { $unwind: "$tags" }:
5{ _id: 1, item: "Course Bundle", tags: "react" }
6{ _id: 1, item: "Course Bundle", tags: "node" }
7{ _id: 1, item: "Course Bundle", tags: "mongo" }

3. Combining $lookup, $unwind, and $group

Find the most popular course tags across all enrollments:

1const popularTags = await db.collection('courses').aggregate([
2 // 1. Flatten the tags array
3 { $unwind: '$tags' },
4 
5 // 2. Group by individual tag and sum enrollments
6 {
7 $group: {
8 _id: '$tags',
9 courseCount: { $sum: 1 },
10 totalEnrollments: { $sum: '$enrollmentCount' }
11 }
12 },
13 
14 // 3. Sort by popularity
15 { $sort: { totalEnrollments: -1 } },
16 
17 // 4. Return top 5 tags
18 { $limit: 5 }
19]);

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What type of relational join does the MongoDB $lookup aggregation stage perform?
Question 2
What data structure does the $lookup stage assign to the output field designated by as?
Question 3
What does the $unwind stage do when applied to an array with 4 elements?
Question 4
What happens by default in $unwind if a document has an empty array [] or the field is missing/null?
Question 5
Why should the foreignField in a joined $lookup collection be indexed?

Next Lesson

Database Indexing Strategies (Single, Compound, TTL) & Query Optimization

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Aggregation Pipeline Architecture: $match, $group, $project & $sortDatabase Indexing Strategies (Single, Compound, TTL) & Query Optimization

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext