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" }
相关推荐
islandzzzz5 小时前
从0开始的SQL表DDL学习(基础语法结构、索引/约束关键字)
数据库·sql·学习
qq_381454995 小时前
数据脱敏全流程解析
java·网络·数据库
qq_348231855 小时前
MySQL 与 PostgreSQL对比
数据库·mysql·postgresql
梁bk5 小时前
苍穹外卖项目总结(一)[MyBatis-Plus,文件上传,Redis]
数据库·redis·mybatis
CNRio5 小时前
Redis:内存中的数据引擎,架构解析与设计指南
数据库·redis·架构
hans汉斯5 小时前
【软件工程与应用】基于大数据的应急救援云平台构建应用研究
大数据·数据库·人工智能·物联网·系统架构·云计算·汉斯出版社
流绪染梦5 小时前
多表联查时处理一对多的信息,将子表字段放入数组
java·数据库
悦数图数据库6 小时前
国产图数据库:开启数据新“视”界 悦数科技
数据库·人工智能
啊巴矲6 小时前
小白从零开始勇闯人工智能Linux初级篇(Navicat Premium及MySQL库(安装与环境配置))
数据库·人工智能·mysql
en-route6 小时前
Redis 作为消息队列的三种使用方式与 Spring Boot 实践
数据库·spring boot·redis