$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.
Practice
$lookup stage do in a MongoDB aggregation pipeline?Solution
Step 1: Understand the purpose of
$lookup$lookupis used to combine documents from two collections by matching fields.Step 2: Compare with other options
Deleting, sorting, or updating documents are different operations and not related to$lookup.Final Answer:
It joins documents from two collections based on a matching field. -> Option BQuick Check:
$lookupjoins collections = A [OK]
- Confusing $lookup with update or delete operations
- Thinking $lookup sorts documents
- Assuming $lookup modifies documents instead of joining
$lookup stage in MongoDB?Solution
Step 1: Identify correct field names in $lookup
The correct keys arefrom,localField,foreignField, andas.Step 2: Check each option
{ $lookup: { from: 'other', localField: 'id', foreignField: 'userId', as: 'joinedData' } } uses all correct keys and syntax. Options A, B, and C have incorrect or missing keys.Final Answer:
{ $lookup: { from: 'other', localField: 'id', foreignField: 'userId', as: 'joinedData' } } -> Option CQuick Check:
Correct $lookup keys = D [OK]
- Using wrong key names like collection or joinAs
- Omitting the 'as' field for output array
- Missing foreignField or localField keys
orders with documents { _id: 1, productId: 101 } and products with documents { _id: 101, name: 'Pen' }, what will be the result of this aggregation on orders?
{ $lookup: { from: 'products', localField: 'productId', foreignField: '_id', as: 'productInfo' } }Solution
Step 1: Match localField and foreignField values
TheproductIdinordersis 101, which matches_id101 inproducts.Step 2: Understand $lookup output
The matching product document is added as an array inproductInfo.Final Answer:
[{ _id: 1, productId: 101, productInfo: [{ _id: 101, name: 'Pen' }] }] -> Option AQuick Check:
Matching product added in array = B [OK]
- Expecting productInfo to be a single object, not an array
- Thinking no match means error instead of empty array
- Ignoring the 'as' field name in output
$lookup stage?
{ $lookup: { from: 'users', localField: 'userId', foreignField: 'id', as: 'userDetails' } }
Assuming the users collection uses _id as the user ID field.Solution
Step 1: Check foreignField correctness
Theuserscollection uses_idas the ID field, soforeignFieldmust be '_id'.Step 2: Verify other fields
localFieldandasare valid; collection name 'users' is correct.Final Answer:
The foreignField should be '_id' instead of 'id'. -> Option DQuick Check:
foreignField must match actual field = C [OK]
- Using wrong foreignField name
- Changing 'as' field unnecessarily
- Mistaking collection name pluralization
students with { _id: 1, name: 'Alice' } and grades with multiple documents per student like { studentId: 1, score: 85 }. How do you write a $lookup to get each student with all their grades in an array called allGrades?Solution
Step 1: Identify matching fields between collections
students._idmatchesgrades.studentId, so these are the fields to join on.Step 2: Write $lookup with correct fields and output array name
Usefrom: 'grades',localField: '_id',foreignField: 'studentId', andas: 'allGrades'.Final Answer:
{ $lookup: { from: 'grades', localField: '_id', foreignField: 'studentId', as: 'allGrades' } } -> Option AQuick Check:
Match student _id to grades studentId = A [OK]
- Swapping localField and foreignField
- Using wrong fields like name or score for join
- Incorrect output array name
Ready to prove it?
Pass the test and this pattern moves unknown
