M121 - Chapter 3 Lab $graphLookup Bonus

I am trying to complete the “bonus” question related to simplifying the $lookup lab using $graphLookup. I understand the point is likely to do the following:

  • Choose the narrowest set of documents to start, which probably means thinking about pursuing the air_alliances collection.
  • Use $graphLookup over $lookup because we can embed a matching filer into the stage.

I am getting a bit tripped up in implementation. In particular, I am unsure about the field selections I am making while trying to do a direct comparison of the top level document. I think I am checking against a list of airlines in an alliance to the name of an airline to decide whether that route should be brought into the document.

However, I’m not sure how to setup the iteration correctly. The following code would be run as db.air_alliances.aggregate(pipeline)

var pipeline = [
  {
    $graphLookup: {
      startWith: "$airlines",
      from: "air_routes",
      connectFromField: "airline.name",
      connectToField: "airline.name",
      as: "routes",
      maxDepth: 0,
      restrictSearchWithMatch: {
        airplane: { $in: ["747", "380"] }
      }
    }
  },
  {
    $project: {
      _id: 0,
      name: 1,
      route_total: { $size: "$routes" }
    }
  }
]

Inspect the field airplane with Compass. The array operator $in will not select the correct documents.

1 Like

Thank you steevej-1495, this solved the problem.

I think I am having trouble understanding the difference between these two queries:

airplane: /747|380/
airplane: { $in: ["747", "380"] }

My understanding is they would look for an airplane value that was 747 or 380 and were comparable. The documentation for $in doesn’t seem to do the trick for me, what am I missing? :pray:

Hi @Niket_Desai,

If you try to look at the airplane field, it has values like shown below:


Note that the airplane field is not an array, so to fetch the field with 380 or 747 value, you need to use regex expression, instead of using $in operator.

Please let me know if you have any additional questions.

Kind Regards,
Sonali

1 Like

Thank you for this – I need to get better at checking what kinds of values are in a field. I made the (bad) assumption this was a string with only one value which proved to be wrong.

In a situation where the field was a string with a single value (one airplane like “330” only), wouldn’t the $in operator allow for matching documents by airplane field with multiple values in the $in array input?

From the $in MongoDB Manual:

The $in operator selects the documents where the value of a field equals any value in the specified array.

Thanks again, everyone!