MongoDB聚合运算符:$isArray

文章目录

$isArray聚合运算符返回操作数是否是一个数组,返回一个布尔值。

语法

js 复制代码
{ $isArray: [ <expression> ] }

使用

<expression>为任何类型的表达式,举例说明:

举例 结果 说明
{ $isArray: "hello" } false "hello"为字符串,作为字符串传递
{ $isArray: [ "hello" ] } false "hello"是一个字符串,作为参数数组的一部分传递
{ $isArray: [ [ "hello" ] ] } true [ "hello" ] 是一个数组,作为参数数组的一部分传递

**注意:**聚合表达式接受可变数量的参数。这些参数通常作为数组传递。但是,当参数是单个值时,可以通过直接传递参数而不将其包装在数组中来简化代码。

举例

使用下面的脚本创建warehouses集合:

js 复制代码
db.warehouses.insertMany( [
   { "_id" : 1, instock: [ "chocolate" ], ordered: [ "butter", "apples" ] },
   { "_id" : 2, instock: [ "apples", "pudding", "pie" ] },
   { "_id" : 3, instock: [ "pears", "pecans"], ordered: [ "cherries" ] },
   { "_id" : 4, instock: [ "ice cream" ], ordered: [ ] }
] )

检查instockordered字段是否为数组。如果两个字段都是数组,则将它们连接起来:

js 复制代码
db.warehouses.aggregate( [
   { $project:
      { items:
          { $cond:
            {
              if: { $and: [ { $isArray: "$instock" },
                            { $isArray: "$ordered" }
                          ] },
              then: { $concatArrays: [ "$instock", "$ordered" ] },
              else: "One or more fields is not an array."
            }
          }
      }
   }
] )

结果:

json 复制代码
{ "_id" : 1, "items" : [ "chocolate", "butter", "apples" ] }
{ "_id" : 2, "items" : "One or more fields is not an array." }
{ "_id" : 3, "items" : [ "pears", "pecans", "cherries" ] }
{ "_id" : 4, "items" : [ "ice cream" ] }
相关推荐
赵渝强老师6 分钟前
【赵渝强老师】Memcached的路由算法
数据库·redis·nosql·memcached
belldeep19 分钟前
groovy 如何遍历 postgresql 所有的用户表 ?
数据库·postgresql
2401_8960081928 分钟前
PostgreSQL
数据库·postgresql
搞不懂语言的程序员37 分钟前
Redis Sentinel如何实现高可用?
数据库·redis·sentinel
wangzhongyudie1 小时前
SQL实战:06交叉日期打折问题求解
数据库·sql
Liudef062 小时前
使用Docker部署MongoDB
mongodb·docker·容器
2401_841003982 小时前
mysql高可用
数据库·mysql
2302_809798322 小时前
【JavaWeb】MySQL(准备篇)
数据库·mysql·datagrip
阿四啊2 小时前
【Redis实战篇】秒杀优化
数据库·redis·缓存
川石课堂软件测试2 小时前
涨薪技术|0到1学会性能测试第65课-SQL捕获阻塞事件
数据库·sql·功能测试·oracle·性能优化·单元测试·tomcat