Docs 菜单
Docs 主页
/
数据库手册
/ / /

$size(聚合)

$size

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

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

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

  • MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本

  • MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本

$size 通过以下语法实现:

{ $size: <expression> }

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

$size 的参数必须解析为数组。如果 $size 的参数缺失或无法解析为数组,则 $size 会出错。

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

以下聚合管道操作使用 $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

在此页面上