← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 6 of 7

$lookup (joins)

$lookup performs a left outer join with another collection in the same database.

In this page:

  1. $lookup (joins)
Syntax
javascript
{ $lookup: {
    from: "other_collection",
    localField: "local_field",
    foreignField: "foreign_field",
    as: "result_array"
} }

$lookup (joins)

$lookup takes from, localField, foreignField and as, and adds an array of matching foreign documents to each input document.

An empty array means no match. Pair it with $unwind to flatten the array.

Frequent joins may suggest embedding the data instead.

Note: Index the foreignField for fast lookups.

Example: $lookup (joins)

bash
test> db.customers.insertMany([{ _id: 1, name: "Ada" }, { _id: 2, name: "Bob" }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.orders.insertMany([{ _id: 10, customerId: 1, total: 50 }, { _id: 11, customerId: 1, total: 20 }, { _id: 12, customerId: 3, total: 5 }])
{ acknowledged: true, insertedIds: { '0': 10, '1': 11, '2': 12 } }
test> db.orders.aggregate([
...   { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } },
...   { $project: { total: 1, customer: "$customer.name" } }
... ])
[
  { _id: 10, total: 50, customer: [ 'Ada' ] },
  { _id: 11, total: 20, customer: [ 'Ada' ] },
  { _id: 12, total: 5, customer: [] }
]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Forgetting the result is an array
  2. Missing an index on foreignField
  3. Using joins everywhere instead of good schema design
Chapter Summary
  • $lookup joins collections
  • from, localField, foreignField, as
  • Result is an array
  • Index the foreign field
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.