MongoDB - The argument to $size must be an Array, but was of type: EOO / missing
You can use the $ifNull
operator here. It seems the field is either not an array or not present by the given error:
{ "$project": {
"people": 1,
"Count": {
"$size": { "$ifNull": [ "$myFieldArray", [] ] }
}
}}
Also you might want to check for the $type
in your $match
in case these do exist but are not an array.
From MongoDB 3.2 and newer, you can use $isArray
to check if your field is an array along with the $cond
operator to return the field on evaluating with $isArray
:
{ "$project": {
"people": 1,
"myFieldArrayCount": {
"$size": {
"$cond": [
{ "$isArray": "$myFieldArray" },
"$myFieldArray",
[]
]
}
}
}}