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" }
相关推荐
NPE~14 分钟前
[手写系列]Go手写db — — 第五版(实现数据库操作模块)
开发语言·数据库·后端·golang·教程·手写系列·手写数据库
有想法的py工程师1 小时前
PostgreSQL 测试磁盘性能
数据库·postgresql
weixin_441455262 小时前
Mysql MVCC
数据库·mysql
Su-RE2 小时前
【ElasticSearch】text 和 keyword 类型区分
java·数据库·elasticsearch
武子康2 小时前
Java-146 深入浅出 MongoDB 数据插入、批量写入、BSON 格式与逻辑查询and or not操作指南
java·开发语言·数据库·sql·mongodb·性能优化·nosql
奥尔特星云大使2 小时前
MySQL快速构建主从(基于GTID)
数据库·mysql·主从复制
小园子的小菜2 小时前
MySQL ORDER BY 深度解析:索引排序规则与关键配置参数阈值
数据库·mysql
wxjlkh3 小时前
Oracle Exadata一体机简介 1千多个W
数据库·oracle
泽虞3 小时前
《Qt应用开发》笔记p3
linux·开发语言·数据库·c++·笔记·qt·面试
XXYBMOOO3 小时前
如何自定义 Qt 日志处理并记录日志到文件
开发语言·数据库·qt