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" ] }
相关推荐
qq_192779872 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272712 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊2 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
tudficdew3 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6523 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
Configure-Handler3 小时前
buildroot System configuration
java·服务器·数据库
2301_821369614 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
电商API_180079052475 小时前
第三方淘宝商品详情 API 全维度调用指南:从技术对接到生产落地
java·大数据·前端·数据库·人工智能·网络爬虫
2401_832131955 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
打工的小王5 小时前
redis(四)搭建哨兵模式:一主二从三哨兵
数据库·redis·缓存