MongoDB — project some fields instead of all inside $lookup

Fred Wong
fredwong-it
Published in
2 min readMar 28, 2019

I am working with MongoDB aggregation and I need to use $lookup to lookup another collection. After the $lookup stage, I only want some fields from another collection, so I look for a solution to project inside the $lookup stage.

I find out the solution on https://docs.mongodb.com $lookup definition.

Equality Match (regular lookup, return all fields from another collection)

{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}

Join Conditions and Uncorrelated Sub-queries ( New in version 3.6.)

{
$lookup:
{
from: <collection to join>,
let: { <var_1>: <expression>, …, <var_n>: <expression> },
pipeline: [ <pipeline to execute on the collection to join> ],
as: <output array field>
}
}

My example

let (optional): you can reference another name from original collection field

$$numbers: this is the field from let block or original collection field name

$number: this is the field from lookup collection

$match: any filter condition, here are using $in

$project: you can project any field you want from the lookup collection

For the new way, you can apply more complex login in $match stage instead of simple field match between 2 collection, it will give you more flexibility and power.

Reference:

--

--