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

Hi Trying to add a new Fields num_fav using $addFields using

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

My understanding is that $setIntersection will retrun empty array even if cast doesn’t match and so size should always have array even of size 0.

Is there something i am missing?

1 Like

Welcome @Sagar_86029,

But what about a scenario where $cast does not exist? :thinking: :bulb:

2 Likes

Thanks, It gives correct result now.

:slightly_smiling_face: :+1:

Can I tack on here to get a bit of a clue as to how to perform the check on cast? $exist filters documents on a field - but if I just want a boolean check on the field (say for a conditional statement), how would I accomplish that? Am I thinking about this correctly?

As long as @Sagar_86029 doesn’t mind :wink:

In this case, just a check for existence is sufficient. If you wanted to go a step further, you could ensure that the field is an array.

1 Like

But $exists provides a filtering mechanism, right?

In other words, if I’m trying to compute the “num_favs” field, then I get where a conditional check would be appropriate, on whether “cast” exists or not. But if I use $exists on cast: { “cast”: { $exists: true } }, then aren’t I just passing through documents that do contain the “casts” field?

I guess I just don’t understand the behavior of $exists here. I would like for it to return a boolean value (for use with a conditional statement), but it returns documents based on whether the field exists or not, right?

That’s right!

Your question is actually kinda out of scope from this thread. @Sagar_86029’s num_fav was correct (conceptually) but he was having problems with the end result because he needed to filter out the nulls in a prior stage. Whereas in your case, you’re trying to work out the num_fav expression. Suggest following this up on your thread.

1 Like

You got it. Sorry for the hijack, @Sagar_86029. Your post helped me a lot and I didn’t even know I needed it.