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 }.
Remember that $project can exclude _id by setting it to 0.
The $lookup uses a pipeline to match products._id with orders.productId. The $project excludes _id, so the embedded productDetails array contains only name and price.
Identify the option that will cause a syntax error in a MongoDB aggregation $lookup stage using a pipeline.
Check how variables are referenced inside the pipeline with let.
Variables defined in let must be referenced inside the pipeline with $$ prefix, e.g., "$$id". Option A uses "$id" which is invalid and causes a syntax error.
You have a $lookup with a pipeline joining orders to products. The products collection is very large. Which option best improves performance?
Indexes help queries run faster, especially on large collections.
Adding an index on products._id helps the $match stage inside the pipeline run efficiently. Using $expr with indexed fields is optimal. Other options either do not improve or degrade performance.
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?
Check how variables from let are used inside the pipeline.
Variables defined in let must be referenced with $$ inside the pipeline. Here, "$pid" is incorrect; it should be "$$pid". Without this, the match fails and returns empty arrays.
Choose the best explanation for why you would use $lookup with a pipeline instead of the simpler localField/foreignField syntax.
Think about flexibility and control over the joined data.
The pipeline form of $lookup lets you apply multiple aggregation stages like $match, $project, $group, etc., on the joined collection. This is not possible with the simple localField/foreignField syntax, which only matches equality.