文档菜单
文档首页
/
MongoDB 手册
/ / /

$size (聚合)

本页

  • 定义
  • 兼容性
  • 语法
  • 行为
  • 示例
$size

计算并返回数组中的总项目数。

您可以使用 $size 在以下环境中部署

  • MongoDB Atlas:云中MongoDB部署的全托管服务

  • MongoDB Enterprise:基于订阅的自托管MongoDB版本

  • MongoDB Community:源代码开放、免费使用且自托管的MongoDB版本

$size 语法如下

{ $size: <expression> }

对于 $size 的参数可以是任何 表达式,只要它解析为数组即可。有关表达式的更多信息,请参阅 表达式运算符

对于 $size 的参数必须解析为数组。如果 $size 的参数缺失或没有解析为数组,则 $size 将出现错误。

考虑一个包含以下文档的 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" }

以下聚合管道操作使用 $size 运算符来返回 colors 数组中的元素数量

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

操作返回以下结果

{ "_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" }

返回

$shift