Chapter 2 - Trying to use $addField to count the num of favorite moviesm

I tried to use $addField where count the num of favorite movies

var favorites = [   "Sandra Bullock",   "Tom Hanks",   "Julia Roberts",   "Kevin Spacey",   "George Clooney"]
 db.movies.aggregate([{$project:{"num_fav":1,"_id":0,"title":1}},{$addFields:{"num_fav":{$setIntersection:["$favorites","$cast"]}},{$count:"$num_fav"}])

It does not reconize “favourites”
Later I got …

After the stage

the only fields left are num_fav and title. The field cast does not exist anymore and the $setIntersection will not work.

The variable favorites is JS variable, it is not a field name. The syntax $favorites is for a field name.

I tried to intersect the arrays .Afterwards, the new field is empty.

{$addFields:{"num_fav":{$setIntersection:[["Sandra Bullock","Tom Hanks","Julia Roberts","Kevin Spacey","George Clooney"],"$reparto"]}}}

What is reparto?

Reparto envolves the field cast

Rerun the aggregation without the $addFields to see if is computed correctly.

If it is then you may try to filter out num_fav:[] to see if some documents remains.

 db.movies.aggregate({$project:{"_id":0,"cast":1,"title":1,"reparto":"$cast"}})

I got that correctly

Yes, that’s correct.

Have you tried:

In the few documents we see in the screenshot, an empty intersection is normal.