$lookup:在管道中连接集合
您将使用 $lookup 在集合之间执行左外连接,并了解跨集合连接带来的性能影响。
$lookup:在管道中连接集合 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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:在管道中连接集合」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。
「$lookup:在管道中连接集合」这节课中我会学到什么?
您将使用 $lookup 在集合之间执行左外连接,并了解跨集合连接带来的性能影响。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 MongoDB Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「$lookup:在管道中连接集合」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 MongoDB Academy 课中编写并运行代码吗?
能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。