$size (聚合)
定义
兼容性
您可以使用 $size
在以下环境中部署
MongoDB Atlas:云中MongoDB部署的全托管服务
MongoDB Enterprise:基于订阅的自托管MongoDB版本
MongoDB Community:源代码开放、免费使用且自托管的MongoDB版本
语法
$size
语法如下
{ $size: <expression> }
行为
示例
考虑一个包含以下文档的 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" }