$size (aggregation)

On this page本页内容

Definition定义

$size

Counts and returns the total number of items in an array.计算并返回数组中的项目总数。

$size has the following syntax:语法如下所示:

{ $size: <expression> }

The argument for $size can be any expression as long as it resolves to an array. $size的参数可以是任何表达式,只要它解析为数组。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

The argument for $size must resolve to an array. $size的参数必须解析为数组。If the argument for $size is missing or does not resolve to an array, $size errors.如果$size的参数丢失或未解析为数组,则$size出错。

Example示例

Consider an inventory collection with the following documents:考虑带有以下文件的inventory集合:

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }
{ "_id" : 4, "item" : "ZZZ1", "description" : "product 4 - missing colors" }
{ "_id" : 5, "item" : "ZZZ2", "description" : "product 5 - colors is string", colors: "blue,red" }

The following aggregation pipeline operation uses the $size operator to return the number of elements in the colors array:以下聚合管道操作使用$size运算符返回colors数组中的元素数:

db.inventory.aggregate([
   {
      $project: {
         item: 1,
         numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} }
      }
   }
] )

The operation returns the following:该操作返回以下内容:

{ "_id" : 1, "item" : "ABC1", "numberOfColors" : 3 }
{ "_id" : 2, "item" : "ABC2", "numberOfColors" : 1 }
{ "_id" : 3, "item" : "XYZ1", "numberOfColors" : 0 }
{ "_id" : 4, "item" : "ZZZ1", "numberOfColors" : "NA" }
{ "_id" : 5, "item" : "ZZZ2", "numberOfColors" : "NA" }