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