Database Manual / Reference / Query Language / Expressions

$size (aggregation)(聚合)

Definition定义

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

Compatibility兼容性

You can use $size for deployments hosted in the following environments:您可以将$size用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

$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. If the argument for $size is missing or does not resolve to an array, $size errors.$size的参数必须解析为数组。如果$size的参数缺失或未解析为数组,则$size错误。

Example示例

Consider an inventory collection with the following documents:考虑使用以下文件进行inventory集合:

db.inventory.insertMany( [
{ _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" }