MongoDB-$size 的参数必须是 Array,但类型为: EOO/miss

尝试使用 冰立方创建 MongoDB 数据源。其思想是将数组的大小作为新字段返回。比如:

$project:
{
"people": 1,
"Count myFieldArray" : {$size : "$myFieldArray" }
}

但是我得到了一些记录,错误如下:

The argument to $size must be an Array, but was of type: EOO

如果字段是空的或者不是数组(消除错误) ,是否有一种大小为0的方法?

30951 次浏览

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.

Alternative solution would be to eliminate the documents with nulls using

$match: {myFieldArray: { $elemMatch: { $exists: true } }}

Also, document fields which are used as arguments to $size by '$' reference (here: "$myFieldArray") must also be the part of projections.

$project:
{
"people": 1,
"myFieldArray":1,
"Count myFieldArray" : {$size : "$myFieldArray" }
}

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",
[]
]
}
}
}}