KoderSolution Logo
HomeArticlesTutorialsForumAI LabRun Code
KoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Engineering Newsletter

Join 100,000+ engineers receiving curated high-signal content weekly.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
🟢

Node.js

Topic Hub & Articles

Node.js Intro

10 min

Recap Quiz

5 Questions

Node.js Get Started

10 min

Node.js Modules

10 min

Node.js HTTP Module

10 min

Recap Quiz

5 Questions

Node.js File System

10 min

Node.js URL Module

10 min

Node.js NPM

10 min

Recap Quiz

5 Questions

Node.js Events

10 min

Node.js Upload Files

10 min

Node.js Email

10 min

Recap Quiz

5 Questions

Node.js Buffer

10 min

Node.js Streams

10 min

Node.js Crypto

10 min

Recap Quiz

5 Questions

Node.js OS Module

10 min

Node.js Path Module

10 min

Node.js Global Objects

10 min

Recap Quiz

5 Questions

Node.js Process

10 min

Node.js Child Processes

10 min

Node.js Worker Threads

10 min

Recap Quiz

5 Questions

Node.js DNS Module

10 min

Node.js Query String

10 min

MySQL Connect

10 min

Recap Quiz

5 Questions

MySQL Create Database

10 min

MySQL Order By

10 min

Recap Quiz

5 Questions

MongoDB Intro

10 min

Recap Quiz

5 Questions

MongoDB Create Database

10 min

MongoDB Create Collection

10 min

MongoDB Insert

10 min

Recap Quiz

5 Questions

MongoDB Find

10 min

MongoDB Query

10 min

MongoDB Sort

10 min

Recap Quiz

5 Questions

MongoDB Delete

10 min

MongoDB Update

10 min

MongoDB Limit

10 min

MongoDB Join

10 min

Progress
0%

0 / 35 Lessons

Node.jsNode.js MongoDB
Lesson

MongoDB Join

10 min reading
Free Course

MongoDB Join: Aggregation Pipelines & $lookup Collection Joins

While MongoDB is a document database, relational data joins across multiple collections can be performed using Aggregation Pipelines and the $lookup stage operator.

$lookup Aggregation Join Pipeline

flowchart TD
    subgraph ORDERS ["orders collection"]
        O1["{ _id: 1, customerId: ObjectId('...'), total: 299.99 }"]
    end
    subgraph USERS ["users collection"]
        U1["{ _id: ObjectId('...'), name: 'Alice', email: '[email protected]' }"]
    end
    ORDERS -->|"$lookup: from 'users', localField 'customerId', foreignField '_id'"| JOINED["Aggregation Result Document"]

Practical Code Example

import { MongoClient } from 'mongodb';

const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);

async function executeLookupAggregationJoin() {
    try {
        await client.connect();
        const db = client.db('kodersolution_no_sql');
        const orders = db.collection('orders');

        // Aggregation Pipeline with $lookup and $unwind
        const pipeline = [
            {
                $lookup: {
                    from: 'users',               // Target collection to join
                    localField: 'customerId',    // Field in orders collection
                    foreignField: '_id',         // Field in users collection
                    as: 'customerDetails'        // Output array field name
                }
            },
            {
                $unwind: '$customerDetails'      // Flatten customerDetails array to object
            },
            {
                $project: {
                    _id: 1,
                    orderTotal: '$totalAmount',
                    customerName: '$customerDetails.name',
                    customerEmail: '$customerDetails.email'
                }
            }
        ];

        const aggregatedResults = await orders.aggregate(pipeline).toArray();
        console.log('Joined Aggregation Results:');
        console.log(aggregatedResults);
    } catch (err) {
        console.error('MongoDB $lookup Aggregation Error:', err.message);
    } finally {
        await client.close();
    }
}

executeLookupAggregationJoin();

Best Practices & Gotchas

  • Index Joined Foreign Fields: Ensure fields specified in foreignField (e.g. users._id) have indexes to optimize $lookup performance.
  • Use $unwind: Use $unwind: '$arrayField' after $lookup to convert the single-match array returned by $lookup into an embedded object.
  • Filter Early with $match: Place $match stages at the very beginning of the pipeline to reduce the number of documents passed to $lookup.

Self-Check Challenge

What is the purpose of the $unwind stage in a MongoDB aggregation pipeline following a $lookup join?

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Recommended Courses & Books

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum