Use variable in $in. Chapter 1 optional lab

When I started on this task I did an $unwind on cast and then was trying to check if the cast member was in the directors array as follows:

db.movies.aggregate([{$unwind:’$cast’},
{$match:{ directors:{$in: [ ‘$cast’ , ‘$directors’ ]} }}])

but it doesn’t return anything,

if you change $name to an actual string like “Lewin Fitzhamon” then you get a bunch of results.

to test i projected out the directors and new name field with the name fixed to “Lewin Fitzhamon”

db.movies.aggregate([{$project:{name:“Lewin Fitzhamon”, directors:1}},{$match:{ directors:{$in: [ ‘Lewin Fitzhamon’ , ‘$directors’ ]} }}])

gives one result but :

db.movies.aggregate([{$project:{name:“Lewin Fitzhamon”, directors:1}},{$match:{ directors:{$in: [ “$name” , ‘$directors’ ]} }}])

gives no result, I thought that $name should be replaced with the value of that field but is that not the case, what am I missing?

Hi,

You are trying to compare two fields in the same document, that’s why $name is treated as a literal value. To resolve to its value, you should use the $expr operator:

db.movies.aggregate([
   {$project:{name:"Lewin Fitzhamon", directors:1}},
   {$match: {
      directors: {$exists: true}, 
      $expr: {$in: ['$name', '$directors']}
    }
  }
])

Please see this doc page for details:

https://docs.mongodb.com/manual/reference/operator/query/expr/

José Carlos

1 Like