Skip to content
Learn Netverks

Lesson

Step 26/36 72% through track

lookup-join-mongodb

$lookup joins

Last reviewed May 28, 2026 Content v20260528
Track mode
none
Means
Read / quiz
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches $lookup joins: document modeling, query operators, and aggregation patterns for MongoDB.

$lookup is your JOIN—index foreign keys and filter the sub-pipeline or performance collapses.

You will apply $lookup joins in contexts like: Order histories with customer names, CMS pages with blocks, and catalogs with variable attributes.

Copy JavaScript shell queries from each lesson into mongosh or MongoDB Atlas Data Explorer—inspect matched documents and explain plans. The in-browser lab (execution_profile: none) ships later; mongosh is the practice path now.

When you can explain the previous lesson's ideas without copying example queries verbatim.

$lookup performs a left outer join to another collection—use indexed foreign keys.

Basic lookup

db.orders.aggregate([
  { $lookup: {
      from: 'customers',
      localField: 'customerId',
      foreignField: '_id',
      as: 'customer'
  }},
  { $unwind: '$customer' },
  { $project: { total: 1, 'customer.name': 1 } }
])

Practice: Run aggregation pipelines in mongosh.

Pipeline lookup (modern)

db.orders.aggregate([
  { $lookup: {
      from: 'customers',
      let: { cid: '$customerId' },
      pipeline: [
        { $match: { $expr: { $eq: ['$_id', '$$cid'] } } },
        { $project: { name: 1 } }
      ],
      as: 'customer'
  }}
])

Important interview questions and answers

  1. Q: $unwind after lookup?
    A: Expands array—empty arrays drop doc unless preserveNullAndEmptyArrays.
  2. Q: Index foreignField?
    A: Index _id or customerId to avoid slow joins.

Self-check

  1. What does as: 'customer' create?
  2. Why index customerId on orders?

Tip: Index localField and foreignField used in $lookup.

Interview prep

$lookup?
Left outer join to another collection.
$unwind?
Deconstructs array field into one doc per element.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • $unwind why?
  • Index foreign keys?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump