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" }
相关推荐
杰克尼1 分钟前
苍穹外卖--day11
java·数据库·spring boot·mybatis·notepad++
LaughingZhu6 分钟前
Product Hunt 每日热榜 | 2026-03-12
大数据·数据库·人工智能·经验分享·搜索引擎
白云如幻10 分钟前
【JDBC】面向对象的思路编写JDBC程序
java·数据库
艾莉丝努力练剑23 分钟前
【Linux进程间通信:共享内存】为什么共享内存的 key 值由用户设置
java·linux·运维·服务器·开发语言·数据库·mysql
悲伤小伞1 小时前
Git_原理及使用_撤销修改_删除文件
数据库·git
fengxin_rou1 小时前
一文读懂 Redis 集群:从哈希槽到透明访问
java·数据库·redis·算法·spring·缓存
m0_635647482 小时前
Qt开发与MySQL数据库教程(二)——MySQL常用命令以及示例
java·开发语言·数据库·mysql
顶点多余2 小时前
数据库——对表的操作
数据库
程序员榴莲2 小时前
MySQL (一):MySQL的安装与启动
数据库·mysql
咖啡の猫2 小时前
Redis 通用命令
数据库·redis·bootstrap