The argument to $size must be an array, but was of type: null

Hello,
I am doing Lab M121 Chapter 2: Basic Aggregation - Utility Stages.
I am getting error
The argument to $size must be an array, but was of type: null
while running following

db.movies.aggregate([{$addFields:{fav_cast:{$filter:{input:"$cast",
as:“fav”,
cond:{$in:["$$fav",[“Sandra Bullock”, “Tom Hanks”, “Julia Roberts”, “Kevin Spacey”, “George Clooney”]]}
}},
rating:"$tomatoes.viewer.rating"}
},
{$addFields:{num_favs:{$size:"$fav_cast"}}
** },**
{$match:{“rating”:{$gte:3},
“num_favs”:{$gte:1}}
},
{$project:{_id:0
,title:1
,rating:1
,cast:1
,fav_cast:1
}
}
])

Appreciate any help!!

The $size operator only support array type, and in movies collection there will be some empty or null values in cast field, you can prevent this using $match operation before this filtering operation, like:

{ $match: { cast: { $type: "array" } } }
… your other stages would be here…


Other suggestion,

you can check both tomatoes.viewer.rating and cast match conditions in first stage no need to add $tomatoes.viewer.rating field in $addFields stage.

1 Like

Thanks This will help!!

I get the output but I am not getting the options given in the answer. I am doing anything wrong?
Following is my code
db.movies.aggregate([{$match:{“tomatoes.viewer.rating”:{$gte:3},
cast: { $type: “array” }}
},
{$addFields:{fav_cast:{$filter:{input:"$cast",
as:“fav”,
cond:{$in:["$$fav",[“Sandra Bullock”, “Tom Hanks”, “Julia Roberts”, “Kevin Spacey”, “George Clooney”]]}
}}}
},
{$addFields:{num_favs:{$size:"$fav_cast"}}
},
{$project:{_id:0
,num_favs:1
,rating:"$tomatoes.viewer.rating"
,title:1
}
},
{$sort:{num_favs:-1,
rating:-1,
title:-1}
},
{$limit:25
}
])

Take a look at https://docs.mongodb.com/manual/reference/operator/aggregation/setIntersection/.

I understand that we should try with $setintersection operator, however now my question is why not $filter operator?

[ $filter ]: Selects a subset of the array to return an array with only the elements that match the filter condition.