0
0
MongoDBquery~5 mins

$lookup for joining collections in MongoDB

Choose your learning style9 modes available
Introduction

$lookup helps you combine data from two collections in MongoDB, like joining tables in a spreadsheet. It lets you see related information together in one place.

You want to see orders with customer details in one result.
You need to combine product info with reviews stored separately.
You want to list employees along with their department info.
You want to merge user profiles with their activity logs.
You want to show blog posts with their comments together.
Syntax
MongoDB
db.collection.aggregate([
  {
    $lookup: {
      from: "otherCollection",
      localField: "fieldInThisCollection",
      foreignField: "fieldInOtherCollection",
      as: "newFieldName"
    }
  }
])

from is the collection you want to join with.

localField is the field in your current collection.

foreignField is the matching field in the other collection.

as is the name of the new array field that will hold matched documents.

Examples
Join orders with customers using customerId and _id fields. The matched customer data will be in customerInfo array.
MongoDB
db.orders.aggregate([
  {
    $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customerInfo"
    }
  }
])
Join posts with comments by matching _id in posts with postId in comments. Comments appear in commentsList array.
MongoDB
db.posts.aggregate([
  {
    $lookup: {
      from: "comments",
      localField: "_id",
      foreignField: "postId",
      as: "commentsList"
    }
  }
])
Sample Program

This example creates two collections: orders and customers. Then it uses $lookup to join orders with their customer details. The result shows each order with an array customerDetails containing matching customer info.

MongoDB
db.orders.insertMany([
  { _id: 1, item: "Pen", customerId: 101 },
  { _id: 2, item: "Notebook", customerId: 102 }
])

db.customers.insertMany([
  { _id: 101, name: "Alice" },
  { _id: 102, name: "Bob" }
])

// Now join orders with customers

db.orders.aggregate([
  {
    $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customerDetails"
    }
  }
]).toArray()
OutputSuccess
Important Notes

The $lookup stage adds an array field even if only one match exists.

If no match is found, the array will be empty.

You can use $unwind after $lookup to flatten the array if you want one document per match.

Summary

$lookup joins two collections by matching fields.

It creates a new array field with matching documents from the other collection.

Useful to combine related data stored separately for easier reading and analysis.