MongoDB聚合运算符:$size

MongoDB聚合运算符:$size

文章目录

$size聚合运算符返回数组中元素的数量。

语法

js 复制代码
{ $size: <expression> }

<expression>为可解析为数组的表达式。

使用

$size 的参数必须解析为数组。如果 $size 的参数丢失或不能析为数组,则 $size 错误。

举例

inventory集合有下列文档:

json 复制代码
{ "_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 运算符返回color数组中的元素数量:

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

操作返回下面的结果:

json 复制代码
{ "_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" }
相关推荐
喜欢猪猪29 分钟前
深入解析MySQL索引:本质、分类、选择及使用原则
数据库·oracle
Gauss松鼠会44 分钟前
GaussDB高安全—数据保护:数据透明加密
网络·数据库·人工智能·sql·安全·开源·gaussdb
解决方案工程师1 小时前
【redis】redis内存管理,过期策略与淘汰策略
数据库·redis·缓存
♡喜欢做梦1 小时前
【MySQL】表的增删查改(CRUD)(上)
数据库·mysql
小林熬夜学编程3 小时前
【MySQL】第九弹---掌握SQL关键操作:更新、删除、插入与聚合分析的秘诀
linux·开发语言·数据库·mysql
web151173602239 小时前
Redis--模糊查询--方法实例
数据库·redis·缓存
TT-Kun9 小时前
MySQL | 库操作
数据库·mysql
GreatSQL社区10 小时前
【GreatSQL优化器-15】index merge
数据库·oracle
PengShuaiD510 小时前
【数据库维护】如何解决Clickhouse数据库Too many parts报错
数据库·clickhouse
TechNomad11 小时前
C++访问MySQL数据库
数据库·c++·mysql