Bird
Raised Fist0
MongoDBquery~20 mins

$lookup with pipeline (advanced join) in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB $lookup Pipeline Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
What is the output of this $lookup with pipeline?

Given two collections orders and products, what will be the result of the following aggregation on orders?

{
  $lookup: {
    from: "products",
    let: { product_id: "$productId" },
    pipeline: [
      { $match: { $expr: { $eq: ["$_id", "$$product_id"] } } },
      { $project: { name: 1, price: 1, _id: 0 } }
    ],
    as: "productDetails"
  }
}

Assume orders has a document { _id: 1, productId: 101, quantity: 2 } and products has { _id: 101, name: "Pen", price: 1.5 }.

A[{ _id: 1, productId: 101, quantity: 2, productDetails: [{ name: "Pen", price: 1.5 }] }]
B[{ _id: 1, productId: 101, quantity: 2, productDetails: [{ _id: 101, name: "Pen", price: 1.5 }] }]
C[{ _id: 1, productId: 101, quantity: 2, productDetails: [] }]
DSyntaxError: Invalid $lookup pipeline syntax
Attempts:
2 left
💡 Hint

Remember that $project can exclude _id by setting it to 0.

📝 Syntax
intermediate
2:00remaining
Which $lookup pipeline syntax is invalid?

Identify the option that will cause a syntax error in a MongoDB aggregation $lookup stage using a pipeline.

A{ $lookup: { from: "items", let: { id: "$itemId" }, pipeline: [ { $match: { $expr: { $eq: ["$_id", "$id"] } } } ], as: "details" } }
B} } "sliated" :sa ,] } } } ]"di$$" ,"di_$"[ :qe$ { :rpxe$ { :hctam$ { [ :enilepip ,} "dImeti$" :di { :tel ,"smeti" :morf { :pukool$ {
C{ $lookup: { from: "items", let: { id: "$itemId" }, pipeline: [ { $match: { $expr: { $eq: ["$_id", "$$id"] } } } ], as: "details" } }
D $lookup: { from: "items", let: { id: "$itemId" }, pipeline: [ { $match: { $expr: { $eq: ["$_id", "$$id"] } } } ], as: "details" } }
Attempts:
2 left
💡 Hint

Check how variables are referenced inside the pipeline with let.

❓ optimization
advanced
2:00remaining
How to optimize $lookup pipeline for large collections?

You have a $lookup with a pipeline joining orders to products. The products collection is very large. Which option best improves performance?

AUse $group in the pipeline to aggregate all products before matching
BUse $unwind on the <code>products</code> collection before $lookup
CRemove the pipeline and use simple localField/foreignField matching
DAdd an index on <code>products._id</code> and use $match with $expr in the pipeline
Attempts:
2 left
💡 Hint

Indexes help queries run faster, especially on large collections.

🔧 Debug
advanced
2:00remaining
Why does this $lookup pipeline return empty arrays?

Given this aggregation on orders:

{
  $lookup: {
    from: "products",
    let: { pid: "$productId" },
    pipeline: [
      { $match: { $expr: { $eq: ["$_id", "$pid"] } } }
    ],
    as: "productInfo"
  }
}

It returns productInfo as empty arrays even though matching documents exist. What is the cause?

AThe <code>productId</code> field does not exist in <code>orders</code>
BVariable <code>pid</code> is referenced incorrectly without <code>$$</code> prefix inside $expr
CThe <code>from</code> collection name is misspelled
DThe <code>$match</code> stage is missing a $project
Attempts:
2 left
💡 Hint

Check how variables from let are used inside the pipeline.

🧠 Conceptual
expert
2:00remaining
What is the main advantage of using $lookup with a pipeline over localField/foreignField?

Choose the best explanation for why you would use $lookup with a pipeline instead of the simpler localField/foreignField syntax.

AIt automatically indexes the joined fields for better performance
BIt always runs faster than localField/foreignField joins
CIt allows complex filtering, transformations, and multiple stages on the joined collection before embedding results
DIt returns results as a flat list instead of an array
Attempts:
2 left
💡 Hint

Think about flexibility and control over the joined data.

Practice

(1/5)
1. What is the main purpose of using $lookup with a pipeline in MongoDB?
easy
A. To create indexes on joined collections automatically
B. To update documents in the joined collection
C. To perform advanced joins with filtering and transformations on the joined data
D. To delete documents from multiple collections at once

Solution

  1. Step 1: Understand $lookup basic function

    $lookup is used to join documents from another collection into the current one.
  2. Step 2: Role of pipeline in $lookup

    Using a pipeline allows filtering and transforming the joined documents before adding them.
  3. Final Answer:

    To perform advanced joins with filtering and transformations on the joined data -> Option C
  4. Quick Check:

    $lookup with pipeline = advanced join [OK]
Hint: Remember: pipeline lets you filter joined data inside $lookup [OK]
Common Mistakes:
  • Thinking $lookup with pipeline updates or deletes data
  • Confusing $lookup with index creation
  • Assuming $lookup merges collections permanently
2. Which of the following is the correct syntax to define variables for use inside the pipeline of a $lookup stage?
easy
A. "params: { var1: \"$field1\", var2: \"$field2\" }"
B. "vars: { var1: \"$field1\", var2: \"$field2\" }"
C. "variables: [ var1: \"$field1\", var2: \"$field2\" ]"
D. "let: { var1: \"$field1\", var2: \"$field2\" }"

Solution

  1. Step 1: Recall $lookup variable syntax

    Variables for the pipeline are defined using the let keyword as an object.
  2. Step 2: Match correct keyword and structure

    Only let with an object of key-value pairs is valid syntax.
  3. Final Answer:

    "let: { var1: \"$field1\", var2: \"$field2\" }" -> Option D
  4. Quick Check:

    Variables in $lookup pipeline = let [OK]
Hint: Use 'let' keyword with object to define variables in $lookup [OK]
Common Mistakes:
  • Using 'vars' or 'variables' instead of 'let'
  • Using array syntax instead of object for variables
  • Omitting the $ sign before field names
3. Given collections orders and products, what will be the output of this aggregation on orders?
{
  $lookup: {
    from: "products",
    let: { prod_id: "$productId" },
    pipeline: [
      { $match: { $expr: { $eq: ["$_id", "$$prod_id"] } } },
      { $project: { name: 1, price: 1, _id: 0 } }
    ],
    as: "productDetails"
  }
}
medium
A. Each order document will have a 'productDetails' field with only product IDs
B. Each order document will have a new field 'productDetails' containing an array with matching product's name and price
C. The query will throw a syntax error due to incorrect variable reference
D. The 'productDetails' field will be a single object, not an array

Solution

  1. Step 1: Understand $lookup with pipeline and let

    The let defines prod_id from orders.productId. The pipeline matches products._id to this variable.
  2. Step 2: Analyze pipeline stages

    The pipeline filters products matching the order's productId and projects only name and price fields, excluding _id.
  3. Final Answer:

    Each order document will have a new field 'productDetails' containing an array with matching product's name and price -> Option B
  4. Quick Check:

    $lookup with pipeline returns array of matched docs [OK]
Hint: Remember $lookup with pipeline returns array in 'as' field [OK]
Common Mistakes:
  • Expecting a single object instead of an array
  • Using wrong variable reference syntax like '$prod_id' instead of '$$prod_id'
  • Forgetting to project fields inside pipeline
4. Identify the error in this $lookup stage:
{
  $lookup: {
    from: "employees",
    let: { empId: "$employeeId" },
    pipeline: [
      { $match: { $expr: { $eq: ["$_id", "$$empId"] } } }
    ],
    as: "employeeInfo"
  }
}
medium
A. Variable reference inside $expr should be "$$empId" instead of "$empId"
B. The let keyword is not allowed inside $lookup
C. The from field must be an array, not a string
D. The as field cannot be named employeeInfo

Solution

  1. Step 1: Check variable usage in $expr

    Variables defined in let must be referenced with double dollar signs $$ inside the pipeline.
  2. Step 2: Identify incorrect variable reference

    The code uses "$empId" instead of "$$empId", causing a runtime error.
  3. Final Answer:

    Variable reference inside $expr should be "$$empId" instead of "$empId" -> Option A
  4. Quick Check:

    Use $$ to reference let variables inside pipeline [OK]
Hint: Use double $$ to reference let variables inside pipeline [OK]
Common Mistakes:
  • Using single $ instead of double $$ for let variables
  • Misplacing let outside $lookup
  • Incorrect data type for 'from' field
5. You want to join orders with products but only include products priced above 100 in the joined array. Which $lookup pipeline correctly achieves this?
hard
A. { $lookup: { from: "products", let: { pid: "$productId" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ["$_id", "$$pid"] }, { $gt: ["$price", 100] } ] } } } ], as: "expensiveProduct" } }
B. { $lookup: { from: "products", localField: "productId", foreignField: "_id", as: "expensiveProduct", pipeline: [ { $match: { price: { $gt: 100 } } } ] } }
C. { $lookup: { from: "products", let: { pid: "$productId" }, pipeline: [ { $match: { _id: "$$pid", price: { $gt: 100 } } } ], as: "expensiveProduct" } }
D. { $lookup: { from: "products", let: { pid: "$productId" }, pipeline: [ { $match: { $expr: { $eq: ["$_id", "$$pid"] } } }, { $match: { price: { $gt: 100 } } } ], as: "expensiveProduct" } }

Solution

  1. Step 1: Understand filtering with $expr and $and

    We must match documents where _id equals the variable and price is greater than 100 in a single $match using $expr and $and.
  2. Step 2: Analyze each option's pipeline

    { $lookup: { from: "products", let: { pid: "$productId" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ["$_id", "$$pid"] }, { $gt: ["$price", 100] } ] } } } ], as: "expensiveProduct" } } correctly uses $expr with $and combining both conditions. { $lookup: { from: "products", localField: "productId", foreignField: "_id", as: "expensiveProduct", pipeline: [ { $match: { price: { $gt: 100 } } } ] } } wrongly uses pipeline with localField/foreignField which is invalid. { $lookup: { from: "products", let: { pid: "$productId" }, pipeline: [ { $match: { _id: "$$pid", price: { $gt: 100 } } } ], as: "expensiveProduct" } } uses invalid $match syntax inside pipeline. { $lookup: { from: "products", let: { pid: "$productId" }, pipeline: [ { $match: { $expr: { $eq: ["$_id", "$$pid"] } } }, { $match: { price: { $gt: 100 } } } ], as: "expensiveProduct" } } splits conditions into two $match stages, but second $match cannot use field without $expr inside pipeline.
  3. Final Answer:

    Option A correctly filters joined products priced above 100 using $expr and $and -> Option A
  4. Quick Check:

    Use $expr with $and for multiple conditions in $lookup pipeline [OK]
Hint: Combine conditions inside one $match using $expr and $and [OK]
Common Mistakes:
  • Using localField/foreignField with pipeline together
  • Splitting conditions into multiple $match without $expr
  • Incorrect $match syntax inside pipeline
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard