Typorithm · medium

$lookup & $unwind

mongo-lookup-unwindmongodbjoinunwindarrays
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn $lookup & $unwind

0%

Aggregation

$lookup joins another collection, putting matches into an array field, and $unwind flattens that array into one document per element so the joined data is easy to use.

$lookup is MongoDB's left outer join: it matches localField against foreignField in the from collection and stores results in an array named by as.

Because matches land in an array, even a one-to-one join leaves you with a single-element array under that field.

$unwind flattens the array, producing one output document per array element, so a downstream stage can read joined fields directly.

01

$lookup is a left outer join into an array field.

02

localField matches foreignField across collections.

03

$unwind flattens the array to one doc per element.

db.orders.aggregate([{ $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }, { $unwind: "$user" }])

Read the implementation

Connect each part of the code to the concept before you type.

1. Join stage

$lookup performs a left outer join, matching localField to foreignField in another collection.

{ $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }

2. Target collection

from names the foreign collection to join against.

from: "users"

3. Join keys

localField on the input is matched to foreignField on the foreign collection.

localField: "userId", foreignField: "_id"

4. Output array

as names the new array field that receives the matched documents.

as: "user"

5. Flatten stage

$unwind turns the array field into one document per element, flattening the single-match join.

{ $unwind: "$user" }

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

$lookup & $unwind: Lesson & Practice · Typorithm | ApplyDjinn