$lookup stage - Chapter 3

Hi,

Regarding discussions on the $lookup stage, the instructor uses an example that matches a localField defined as an array ( i.e. “air_alliances.airlines”) , to a scalar foreignField ( i.e. “air_airlines.name”).

The documentation implies an $unwind is required prior to a $lookup ( https://docs.mongodb.com/v3.6/reference/operator/aggregation/lookup/#use-lookup-with-an-array), specifically to flatten out the input array field but the example doesn’t actually do that i.e.

db.air_alliances.aggregate([
{
$unwind : “$airlines”
},
{
“$lookup”: {
“from”: “air_airlines”,
“localField”: “airlines”,
“foreignField”: “name”,
“as”: “airlines”
}
}
]).pretty()

As opposed to the below from the example:

db.air_alliances.aggregate([
{
“$lookup”: {
“from”: “air_airlines”,
“localField”: “airlines”,
“foreignField”: “name”,
“as”: “airlines”
}
}
]).pretty()

Both produce entirely different results so any clarification will be appreciated as it’ll assist in completing the subsequent lab

Thanks

Hi,

When the localField is an array, it performs a $in, that’s why the output is completely different, but using $unwind first is not required. Please see the note regarding localField in the doc page you posted.

Please note that in the $lookup lab you do not need to $unwind first.

José Carlos

Thanks Jose

Noted and resolved

Regards

You are welcome!

José Carlos

Hello,

So on the localField it does an $in, so it allows you to use an array to lookup from, however when I try it with a array as a foreignField, it seems to complain.

Is this possible, and my code is just incorrect, or is it the array can only be in the localField.

Thank you

Edit: Found the mistake in my code, so I can lookup on an foreignKey, which is an array.

PS - The $unwind, to clear the null arrays from the document set, post $lookup, was more elegant than using $elemMatch{$exists: true} .