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" }
相关推荐
数据知道12 分钟前
一文掌握 MongoDB 详细安装与配置(Windows / Linux / macOS 全平台)
linux·数据库·windows·mongodb·macos
Knight_AL13 分钟前
Flink 状态管理详细总结:State 分类、Keyed State 实战、Operator State、TTL、状态后端选型
前端·数据库·flink
ADRU13 分钟前
Dify API 数据库连接与 Session 管理架构调研
数据库·架构
zhglhy15 分钟前
Redis Cluster 的数据分片机制
数据库·redis·缓存
奥特曼_ it19 分钟前
【NLP舆情分析】基于python微博舆情分析可视化系统(完整系统源码+数据库+详细部署教程)✅
数据库·python·自然语言处理
Mr__Miss22 分钟前
Mysql的redo log和undo log
数据库
码界奇点1 小时前
深入解析MySQL9主从复制架构详解从原理到实战优化
数据库·sql·架构·可用性测试
Miha_Singh1 小时前
查询优化综述:《A Survey of Query Optimization in Large Language Models》
数据库·人工智能·语言模型·查询优化·查询改写
打工的小王2 小时前
Redis(一)redis的下载安装与使用
数据库·redis·缓存
煎蛋学姐2 小时前
SSM医患交流m8996(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·ssm 框架·医患交流系统