$lookup: 파이프라인에서 컬렉션 조인하기
학습자는 $lookup을 사용해 컬렉션 간 왼쪽 외부 조인을 수행하고 컬렉션 간 조인이 성능에 미치는 영향을 이해합니다.
$lookup: 파이프라인에서 컬렉션 조인하기은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why $lookup Exists
MongoDB is designed around embedding related data, but sometimes data must live in separate collections—especially in many-to-many or one-to-many scenarios where embedding would cause unbounded document growth. The $lookup stage performs a left outer join between the current collection (the 'left' side) and another collection (the 'right' side), allowing you to bring related data together server-side in a single aggregation pipeline.
Basic $lookup Syntax
The basic $lookup has four required fields: from (the collection to join), localField (field in the input document), foreignField (field in the joined collection), and as (name of the array field added to the output). The result is an array because one document might match multiple documents in the joined collection.
// Join orders with their product details
db.orders.aggregate([
{ $lookup: {
from: 'products', // collection to join
localField: 'productId', // field in orders
foreignField: '_id', // field in products
as: 'productDetails' // output array field name
}}
]);
// Each order now has a 'productDetails' array with matching productsUnwinding the Joined Array
Since $lookup always produces an array in the as field, you often need to flatten it to access sub-fields directly. If you know the join is one-to-one (e.g., joining by a unique _id), use $unwind immediately after $lookup to flatten the array into a single embedded object. Be aware that $unwind removes documents that have no matches (empty array).
db.orders.aggregate([
{ $lookup: {
from: 'products',
localField: 'productId',
foreignField: '_id',
as: 'product'
}},
// Flatten: productDetails array -> productDetails object
{ $unwind: '$product' },
// Now access product fields directly:
{ $project: { orderId: '$_id', amount: 1, 'product.name': 1, 'product.price': 1 } }
]);$lookup as a Left Outer Join
$lookup performs a left outer join: every document from the left (input) collection is included in the output, even if there are no matching documents in the right (foreign) collection. In that case, the as field is set to an empty array. This differs from an inner join where non-matching left documents would be excluded. To filter out non-matching documents, add a $match after the $lookup.
db.orders.aggregate([
{ $lookup: {
from: 'products',
localField: 'productId',
foreignField: '_id',
as: 'product'
}},
// Simulate inner join: exclude orders with no matching product
{ $match: { product: { $ne: [] } } },
// Or equivalently:
{ $match: { 'product.0': { $exists: true } } }
]);Pipeline $lookup for Complex Joins
The advanced form of $lookup uses a pipeline option instead of simple field matching, allowing arbitrary pipeline stages to run on the joined collection before the join. You can filter, project, and compute inside the joined pipeline using $$let variables to pass values from the parent document. This enables complex conditional joins and joins with inequality conditions.
// Join only active discounts for each product
db.products.aggregate([
{ $lookup: {
from: 'discounts',
let: { productId: '$_id', price: '$price' }, // pass parent fields
pipeline: [
{ $match: {
$expr: {
$and: [
{ $eq: ['$productId', '$$productId'] }, // use $$var
{ $eq: ['$active', true] }
]
}
}},
{ $project: { amount: 1, expiresAt: 1 } }
],
as: 'activeDiscounts'
}}
]);Self-Join With $lookup
You can use $lookup to join a collection with itself—for example, to find a user's manager by looking up the manager's ID in the same users collection. Set from to the same collection name as the input collection. Self-joins are useful for hierarchical data or when a document references another document in the same collection.
// Self-join: attach manager details to each employee
db.employees.aggregate([
{ $lookup: {
from: 'employees', // same collection
localField: 'managerId',
foreignField: '_id',
as: 'manager'
}},
{ $unwind: { path: '$manager', preserveNullAndEmptyArrays: true } },
{ $project: {
name: 1,
department: 1,
'manager.name': 1
}}
]);$lookup Performance Considerations
$lookup can be expensive if the joined collection is large and unindexed. MongoDB creates a temporary index on the foreign field during the join if one doesn't already exist, but this index is not persisted. For repeated $lookup operations on the same field, create a permanent index on the foreign collection's field to avoid this overhead on every query.
// Ensure foreignField is indexed in the joined collection
// 'products' is the joined collection, '_id' is always indexed
// But for custom fields, index explicitly:
db.discounts.createIndex({ productId: 1, active: 1 });
// Now this $lookup is fast because productId is indexed
db.products.aggregate([{
$lookup: {
from: 'discounts',
localField: '_id',
foreignField: 'productId', // indexed!
as: 'discounts'
}
}]);Multiple $lookup Stages
You can chain multiple $lookup stages to join more than two collections in a single pipeline. Each $lookup adds a new array field to the document stream. Keep in mind that each additional join multiplies the data volume and computational cost—avoid joining more than 2-3 large collections in a single pipeline. If you find yourself doing many joins, reconsider whether embedding some data would simplify the schema.
db.orders.aggregate([
// Join 1: product details
{ $lookup: { from: 'products', localField: 'productId', foreignField: '_id', as: 'product' } },
{ $unwind: '$product' },
// Join 2: customer details
{ $lookup: { from: 'customers', localField: 'customerId', foreignField: '_id', as: 'customer' } },
{ $unwind: '$customer' },
{ $project: {
_id: 1, amount: 1,
'product.name': 1,
'customer.email': 1
}}
]);Reducing $lookup Data With a Pipeline Sub-Projection
In the pipeline form of $lookup, include a $project stage inside the join's pipeline to fetch only the fields you need from the joined collection. This reduces the data transferred from the joined collection and the memory footprint of the join result. Never join entire large documents if you only need two or three fields from them.
db.orders.aggregate([{
$lookup: {
from: 'products',
let: { pid: '$productId' },
pipeline: [
{ $match: { $expr: { $eq: ['$_id', '$$pid'] } } },
// Only fetch name and imageUrl, not the full product document
{ $project: { _id: 0, name: 1, imageUrl: 1, price: 1 } }
],
as: 'product'
}
}]);$lookup vs Embedding: The Trade-Off
Every $lookup is a trade-off: it gives you flexibility at query time but adds latency compared to reading embedded data in a single document. Use $lookup when: the joined data changes frequently and you want a single source of truth; the data relationship is many-to-many; or embedding would create unbounded document growth. Use embedding when reads are frequent and the related data rarely changes independently.
// When to embed (avoid $lookup):
// - User profile with 2-3 addresses (bounded, read often together)
// { user: { name, email, addresses: [...] } }
// When to $lookup (use references):
// - Orders referencing products (products change, shared by many orders)
// { order: { productId: ObjectId(...), qty: 2 } }
// -> $lookup products on readConcise Join With $lookup on Arrays
$lookup also handles the case where localField is an array of IDs. MongoDB automatically performs a multi-value join: for each element in the localField array, it looks up the matching document in the foreign collection and collects all results. This makes it easy to join a post's tagIds array to a tags collection in one step.
// Post document: { title: '...', tagIds: [ObjectId1, ObjectId2] }
// Join all tag documents for a post's tagIds array:
db.posts.aggregate([{
$lookup: {
from: 'tags',
localField: 'tagIds', // this is an array!
foreignField: '_id',
as: 'tags'
}
}]);
// tags array in output contains one doc per ObjectId in tagIdsQuick Check
Test your understanding of $lookup in the aggregation pipeline.
Lesson Recap
In this lesson you learned: $lookup performs a left outer join between two collections using matching field values, the pipeline form of $lookup supports complex conditional joins with $$let variables, and indexing the foreign field dramatically improves join performance. Next up we explore $unwind for deconstructing array fields.
자주 묻는 질문
“$lookup: 파이프라인에서 컬렉션 조인하기” 강의는 무료인가요?
네 — “$lookup: 파이프라인에서 컬렉션 조인하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“$lookup: 파이프라인에서 컬렉션 조인하기”에서 뭘 배우나요?
학습자는 $lookup을 사용해 컬렉션 간 왼쪽 외부 조인을 수행하고 컬렉션 간 조인이 성능에 미치는 영향을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“$lookup: 파이프라인에서 컬렉션 조인하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- $lookup: 파이프라인에서 컬렉션 조인하기
- $unwind: 배열 필드 분해하기
- $addFields, $replaceRoot, $mergeObjects
- $out과 $merge: 파이프라인 결과 기록하기