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

Hi,

I get an error because the argument to $size is null
I add a $cond control to check if argument is null, but still have an error message

db.ProductV2.find(
{
  $expr: {
    $gt: [
      {$size:
        {$cond:
          [
            {$ne:['sizes',null]},
            {$filter: 
              {
                input:'$sizes.sku',
                as:'sku',
                cond:{$ne:[{$substr:['$$sku',0,11]},'$optionId']}
              }
            },
            []
          ]
        }
      },
      0
    ]
  }
}
)

I don’t know how to solve my problem

Hi @emmanuel_bernard and welcome to the community forum!!

Can you help us with few information on the above mentioned error:

  1. MongoDB version
  2. Sample document to try the above query on the collection.
  3. Expected output from the above query.

Thanks
Aasawari

Inside $expr you must use $ in front of field name to access the field value.

With

you are testing if the string sizes is not null. You want $sizes instead.

2 Likes

Hi Steeve,

Thanks a lot.

I found this comment in a post “You cannot use $exists within a $expr; only aggregation expressions are allowed”.

Here is my solution

db.ProductV2.find(
{
  $and: [
    {sizes:{$exists:true}},
    {
      $expr: {
        $gt: [
          {$size:
            {$filter: 
              {
                input:'$sizes.sku',
                as:'sku',
                cond:{$ne:[{$substrCP:['$$sku',0,11]},'$optionId']}
              }
            }
          },
          0
        ]
      }
    }
  ]
}
)
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.