$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.
$lookup for joining collections in 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.
customerInfo array.db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerInfo"
}
}
])commentsList array.db.posts.aggregate([
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "postId",
as: "commentsList"
}
}
])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.
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()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.
$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.