Size dont work with aggregation

Size dont work with aggregation
Mongodb 4.2.8

db.Col.aggregate( [
 { $match: { "Symbol" : "x"  }},
 { $group: { _id: "$GroupTime", total: { $size: "$MyArray" } } }
 ])

return error
“errmsg” : “unknown group operator ‘$size’”,
“code” : 15952,

It is not a group operator. These are the group operators: Accumulators $group. But, you can use the $size in a $project (or $addFields) stage.

What is it you are trying to do?

1 Like

how will be look like query with $addFields ?

In general, you use the $size operator with a field MyArray in a document: { _id: 1, MyArray: [ "apples", "bananas", "oranges" ] }

The size of the array can be determined as follows:

{ $addFields: { arraySize: { $size: "$MyArray" } } }

This will get the output as: arraySize: 3

1 Like