Is there a way to query array fields with size greater than some specified value?

After the lecture on $size operator, I was wondering if I can query movies that were shot in more than one location, so I executed this line of command in the Mongo Shell:

{countries:{$size: {$gt: 1}}}

Then I got an error:
"$size needs a number"

Now I understand that the $size operator accepts only numeric values, but is there a way to query what I wanted? Thanks!

The following

{ “countries.1” : { “$exists” : true } }

will do what you want. If you want $gt : 3, you would use countries.3 as array indexes starts at 0.

1 Like

Hi @Thomas_Kwok,

Yes, you can do that using $expr operator along with the $size operator.


Here, we are using $expr operator to filter out all those documents which has size greater than or equal to 4.

Hope it helps!

Let us know if you have any questions.

~ Shubham