$isArray (聚合)
定义
$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: [ ] } ] )
检查 instock
和 ordered
字段是否为数组。如果两个字段都是数组,则将它们连接
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" ] }