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" }
相关推荐
咖丨喱32 分钟前
【Action帧简要分析】
服务器·数据库·asp.net
没饭吃!33 分钟前
NHibernate案例
数据库·hibernate
泷羽Sec-静安1 小时前
OSCP官方靶场-Solstice WP
服务器·网络·数据库
IvanCodes1 小时前
Oracle 视图
大数据·数据库·sql·oracle
德育处主任Pro2 小时前
「py数据分析」04如何将 Python 爬取的数据保存为 CSV 文件
数据库·python·数据分析
许白掰2 小时前
Linux入门篇学习——Linux 编写第一个自己的命令
linux·运维·数据库·嵌入式硬件·学习
打不了嗝 ᥬ᭄2 小时前
文件系统----底层架构
linux·运维·数据库
网小鱼的学习笔记3 小时前
python中MongoDB操作实践:查询文档、批量插入文档、更新文档、删除文档
开发语言·python·mongodb
亲爱的非洲野猪3 小时前
Oracle与MySQL详细对比
数据库·mysql·oracle
GeekAGI3 小时前
MongoDB Shell 数据归档指南:将大表数据归档到另一表
mongodb