Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$size(聚合)

在此页面上

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

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

可以使用 $size 查找托管在以下环境中的部署:

  • MongoDB Atlas :用于在云中部署 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(聚合)