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" }
相关推荐
Raink老师6 小时前
【AI面试临阵磨枪-94】Skill 安全:注入、越权、数据泄露、恶意代码、沙箱?
数据库·安全·面试
程序员二叉6 小时前
【Redis】 缓存三大问题 + 大Key/热Key 全面解析
数据库·redis·缓存
mit6.8246 小时前
Agent Memory Management
数据库·人工智能
We Just Keep growing6 小时前
【MySQL进阶篇】—— 视图、存储过程、存储函数、触发器
数据库·mysql
梦想的颜色7 小时前
MySQL 数据存储结构与查询执行生命周期深度解析
运维·数据结构·数据库·mysql·线程·优化
电商API_180079052477 小时前
免 TOP 入驻,第三方淘宝商品详情 API 快速接入与代码示例
java·大数据·开发语言·数据库·爬虫·数据分析
神龙斗士2408 小时前
增删改查操作
数据库·mysql
Elastic 中国社区官方博客8 小时前
13.7万人,零人工决策:使用 Elasticsearch 实现智能体驱动的灾害响应系统
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
yuzhiboyouye8 小时前
sql增删改查怎么写?有时会不会有联表查询的增删查改
数据库·sql
jingyu飞鸟8 小时前
openEuler 22.03 LTS SP4安装华为opengauss 22.03 LTS版本数据库,一键复制安装使用,保姆级教程
数据库·华为