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" }
相关推荐
FungLeo15 分钟前
FengCMS · PHP+MySQL 升级实录 ·双数据库验证:MySQL8.4与MariaDB 10.11的兼容矩阵
数据库·mysql·php·工程实践·fengcms
XW9632582 小时前
除湿机行业组织能力与人才地图报告
大数据·服务器·网络·数据结构·数据库·人工智能
Decay__3 小时前
PostgreSQL 性能调优方法论 —— pg_stat_statements、EXPLAIN ANALYZE、瓶颈定位流程与参数基线
运维·数据库·sql·postgresql
前端兰博5 小时前
分库分表
数据库
智能收银研究所6 小时前
收银系统选型对比:美团、客如云、拉卡拉、收钱吧各适合什么门店
java·前端·数据库
七夜zippoe8 小时前
金仓 Kingbase 安装与 Java 连接(保姆级):从装库到 JDBC 跑通全记录
java·数据库·jdbc·kingbase·金仓
stormsha8 小时前
中文路径让 MySQL 起不来:Failed to find valid data directory 与 Illegal byte sequence
运维·数据库·mysql
stormsha9 小时前
MySQL 报 `data directory has files in it`:初始化失败一次,之后就永久起不来
运维·数据库·mysql
YYYing.10 小时前
【Redis剑指offer系列 (一) 】Redis数据结构
数据库·redis·缓存·八股
csdn_aspnet10 小时前
使用 Docker 配置 PostgreSQL 和 pgAdmin 4
数据库·docker·postgresql·pgadmin4