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" ] }
相关推荐
等....8 小时前
Minio使用
数据库
win x9 小时前
Redis 使用~如何在Java中连接使用redis
java·数据库·redis
迷枫71210 小时前
DM8 数据库安装实战:从零搭建达梦数据库环境(附全套工具链接)
数据库
XDHCOM11 小时前
PostgreSQL 25001: active_sql_transaction 报错原因分析,故障修复步骤详解,远程处理解决方案
数据库·sql·postgresql
卤炖阑尾炎11 小时前
PostgreSQL 日常运维全指南:从基础操作到备份恢复
运维·数据库·postgresql
daad77712 小时前
wifi_note
运维·服务器·数据库
xixingzhe213 小时前
Mysql统计空间增量
数据库·mysql
程序员萌萌13 小时前
Redis的缓存机制和淘汰策略详解
数据库·redis·缓存机制·淘汰策略
不剪发的Tony老师14 小时前
SQLite 3.53.0版本发布,重要更新
数据库·sqlite
Bczheng114 小时前
九.Berkeley DB数据库 序列化和钱包管理(1)
数据库