Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
Aggregation Commands
Next article icon

MongoDB Aggregation $lookup

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB $lookup stage is a powerful feature within the Aggregation Framework that allows us to perform a left outer join between collections. This allows developers to combine related data from multiple collections within the same database which is highly useful for scenarios requiring relational-like queries in a NoSQL environment.

Understanding the MongoDB $lookup syntax and usage are important for efficiently performing complex queries and retrieving related data in a MongoDB database. In this article, we will explain the structure of MongoDB's $lookup stage, demonstrate its implementation with a practical example, and explain how it performs a left outer join to merge data from multiple collections.

MongoDB Aggregation $lookup

The $lookup operator in MongoDB allows us to perform a left outer join between documents from two collections, similar to SQL joins. This means that documents from the primary collection (input) will be matched with documents from the foreign collection based on a given condition. It's useful for combining data from different collections for analysis or reporting purposes. If no match is found, the result will still include the input document with an empty array, providing flexibility in data retrieval.

Why Use $lookup?

  • Combine data across multiple collections without creating redundant data.
  • Eliminate the need for multiple queries by fetching related data in a single operation.
  • Perform SQL-like joins while leveraging MongoDB's flexible document structure.
  • Efficient reporting & analytics by aggregating data from different collections

Syntax:

{
$lookup: {
from: <foreignCollection>,
localField: <fieldInInputDocument>,
foreignField: <fieldInForeignDocument>,
as: <outputArrayField>
}
}

Key Terms

  • from: The name of the foreign collection to join with.
  • localField: The field from the input documents that will be used for matching.
  • foreignField: The field from the foreign collection that will be used for matching.
  • as: The name of the output array field that will contain the joined documents.

Examples of MongoDB Aggregation $lookup

To understand MongoDB Aggregation $lookup we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called orders and customers which contains various information shown as below:

Collection: orders

[
{
"_id": ObjectId("60f9d7ac345b7c9df348a86e"),
"order_number": "ORD001",
"customer_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"customer_details": [
{
"_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"name": "John Doe",
"email": "[email protected]"
}
]
},
// Other order documents...
]

Collection: customers

[
{
"_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"name": "John Doe",
"email": "[email protected]"
},
// Other customer documents...
]

Example 1: Perform a Single Equality Join with $lookup

Let's Retrieve orders from the orders collection along with corresponding customer details from the customers collection based on matching customer_id and _id.

Query:

db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customer_id",
foreignField: "_id",
as: "customer_details"
}
}
])

Output:

[
{
"_id": ObjectId("60f9d7ac345b7c9df348a86e"),
"order_number": "ORD001",
"customer_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"customer_details": [
{
"_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"name": "John Doe",
"email": "[email protected]"
}
]
},
// Other order documents with appended customer details...
]

Explanation:

This query uses the $lookup stage to perform a left outer join between the orders collection and the customers collection. It matches customer_id from the orders collection with _id in the customers collection and appends the matched customer details to an array field named customer_details. If no match is found, the customer_details array will be empty.

Example 2: Use $lookup with an Array

By default, the $lookup operator includes an array field (as) in the output documents, even if no matches are found in the foreign collection. This array field will be empty ([]) for unmatched documents.

Continuing from the previous example, suppose there are orders with customer_id values that do not exist in the customers collection. The $lookup operator will still include these orders in the output, with an empty customer_details array for unmatched documents.

Query:

db.orders.aggregate([
{
$lookup: {
from: "customers",
let: { customerId: "$customer_id" },
pipeline: [
{
$match: {
$expr: { $in: ["$_id", "$$customerId"] }
}
}
],
as: "customer_details"
}
}
])

Output:

[
{
"_id": ObjectId("60f9d7ac345b7c9df348a86e"),
"order_number": "ORD001",
"customer_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"customer_details": [
{
"_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"name": "John Doe",
"email": "[email protected]"
}
]
},
// Other order documents...
]

Explanation:

  • In this example, $lookup is used with an array and a pipeline ($match and $expr) to join orders with customers.
  • It matches customer_id from orders with _id in customers, appending customer details into customer_details.

Example 3: Use $lookup with $mergeObjects

We can include multiple $lookup stages in an aggregation pipeline to perform multiple join operations with different foreign collections. Suppose we want to enhance orders documents with details from both customers and products collections. We can include multiple $lookup stages to achieve this:

Query:

db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customer_id",
foreignField: "_id",
as: "customer_info"
}
},
{
$addFields: {
customer_details: {
$mergeObjects: "$customer_info"
}
}
}
])

Output:

[
{
"_id": ObjectId("60f9d7ac345b7c9df348a86e"),
"order_number": "ORD001",
"customer_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"customer_info": [
{
"_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"name": "John Doe",
"email": "[email protected]"
}
],
"customer_details": {
"_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"name": "John Doe",
"email": "[email protected]"
}
},
// Other order documents...
]

Explanation:

  • Here, $lookup is followed by $mergeObjects to combine fields from customers with fields in orders.
  • It merges matched customer details into a single customer_details object within each order document.

Example 4: Perform Multiple Joins and a Correlated Subquery with $lookup

When working with multiple related collections in MongoDB, we may need to join data from multiple sources. The $lookup stage allows us to fetch data from different collections in a single aggregation pipeline, improving efficiency and query performance.

Query:

db.orders.aggregate([
{
$lookup: {
from: "customers",
let: { customerId: "$customer_id" },
pipeline: [
{
$match: {
$expr: { $in: ["$_id", "$$customerId"] }
}
},
{
$lookup: {
from: "products",
localField: "_id",
foreignField: "customer_id",
as: "products_ordered"
}
}
],
as: "customer_details"
}
}
])

Output:

[
{
"_id": ObjectId("60f9d7ac345b7c9df348a86e"),
"order_number": "ORD001",
"customer_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"customer_details": [
{
"_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"name": "John Doe",
"email": "[email protected]",
"products_ordered": [
{
"_id": ObjectId("60f9d7ac345b7c9df348a870"),
"customer_id": ObjectId("60f9d7ac345b7c9df348a86d"),
"product_name": "Product A"
}
]
}
]
},
// Other order documents...
]

Explanation:

  • This complex query uses multiple $lookup stages within a pipeline. It first matches customer_id from orders with _id in customers, then performs a subquery $lookup to match customer _id with customer_id in products.
  • It enhances order documents with nested arrays of products ordered by each customer.

Conclusion

MongoDB’s $lookup stage offers an effective way to communicate relational joins within the NoSQL ecosystem and crteate the gap between MongoDB’s document-based structure and the need for combined data from multiple collections. By learning the MongoDB $lookup syntax and usage the developers can execute complex queries, retrieve related data more efficiently and enhance the functionality of their applications. Whether it's for performing a simple join or handling more intricate queries, understanding MongoDB $lookup is a key component in leveraging MongoDB’s full potential.


Next Article
Aggregation Commands

K

kumarsar29u2
Improve
Article Tags :
  • MongoDB
  • Databases

Similar Reads

  • Aggregation in MongoDB
    Aggregation in MongoDB is a powerful framework that allows developers to perform complex data transformations, computations and analysis on collections of documents. By utilizing the aggregation pipeline, users can efficiently group, filter, sort, reshape, and perform calculations on data to generat
    7 min read
  • MongoDB Aggregation $group Command
    The $group command in MongoDB's aggregation framework is a powerful tool for performing complex data analysis and summarization. It allows users to group documents based on specified keys and apply aggregate functions such as sum, count, average, min, max, and more. In this article, we will explore
    6 min read
  • Python MongoDB - $group (aggregation)
    MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. In this article, we will see the use of $group in MongoDB using Python. $group operation In PyMongo, the Aggregate Method is
    3 min read
  • MongoDB Aggregation $out
    MongoDB's aggregation framework offers powerful tools for data analysis and the $out stage for data processing and analysis, with the $out stage playing a crucial role in persistently storing the results of an aggregation pipeline. This feature is highly beneficial for efficient data analysis, repor
    5 min read
  • Aggregation Commands
    Aggregation commands in MongoDB are powerful tools within the aggregation pipeline framework that enable complex data processing and analysis. These commands allow operations such as grouping, sorting and filtering data by making them essential for generating reports, summarizing data and performing
    6 min read
  • MongoDB Aggregation Pipeline $limit
    The MongoDB aggregation pipeline is a powerful tool for data processing and transformation, allowing users to perform efficient filtering, sorting, grouping, and reshaping of documents. Among its various stages, the $limit stage is essential for restricting the number of documents that flow through
    7 min read
  • DynamoDB - Aggregation
    In today's data-driven world, the ability to intelligently transform big data into actionable insights is crucial for the success of business. DynamoDB, offered by Amazon, act as a versatile and scalable NoSQL database solution known for its flexibility and performance levels. Aggregation plays a fu
    7 min read
  • Mongoose Aggregate.prototype.lookup() API
    The Mongoose Aggregate prototype.lookup() method of the Mongoose API is used to perform aggregation tasks. It allows us to perform left join the operation between the collection in the same database to filter out the documents based on requirements and conditions. Let us understand lookup() method u
    4 min read
  • MongoDB Aggregation $first Operator
    MongoDB's aggregation framework offers a rich set of operators for data manipulation and analysis. One such operator is $first, which retrieves the first document from a group of documents. In this article, we will learn about the $first operator in MongoDB aggregation by covering its concepts and u
    4 min read
  • Aggregation in MongoDB using Python
    MongoDB is free, open-source,cross-platform and document-oriented database management system(dbms). It is a NoSQL type of database. It store the data in BSON format on hard disk. BSON is binary form for representing simple data structure, associative array and various data types in MongoDB. NoSQL is
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences