MongoDB聚合运算符:$isArray

文章目录

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

语法

{ $isArray: [ <expression> ] }

使用

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

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

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

举例

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

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字段是否为数组。如果两个字段都是数组,则将它们连接起来:

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."
            }
          }
      }
   }
] )

结果:

{ "_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" ] }
  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值