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" ] }
相关推荐
考虑考虑1 小时前
postgressql更新时间
数据库·后端·postgresql
甄超锋1 小时前
python sqlite3模块
jvm·数据库·python·测试工具·django·sqlite·flask
HMBBLOVEPDX2 小时前
MySQL的锁:
数据库·mysql
数据皮皮侠3 小时前
最新上市公司业绩说明会文本数据(2017.02-2025.08)
大数据·数据库·人工智能·笔记·物联网·小程序·区块链
GeekAGI3 小时前
PyMongo 中 `ServerSelectionTimeoutError` 和 `NetworkTimeout` 异常的区别
mongodb
小云数据库服务专线3 小时前
GaussDB数据库架构师修炼(十六) 如何选择磁盘
数据库·数据库架构·gaussdb
码出财富4 小时前
SQL语法大全指南
数据库·mysql·oracle
异世界贤狼转生码农6 小时前
MongoDB Windows 系统实战手册:从配置到数据处理入门
数据库·mongodb
QuZhengRong6 小时前
【数据库】Navicat 导入 Excel 数据乱码问题的解决方法
android·数据库·excel
码农阿豪6 小时前
Windows从零到一安装KingbaseES数据库及使用ksql工具连接全指南
数据库·windows