$isArray (aggregation)
On this page本页内容
Definition定义
$isArray
-
Determines if the operand is an array. Returns a boolean.确定操作数是否为数组。返回布尔值。$isArray
has the following syntax:具有以下语法:{ $isArray: [ <expression> ] }
Behavior行为
The <expression>
can be any valid expression. <expression>
可以是任何有效的表达式。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
{ $isArray: "hello" } | false | "hello" |
{ $isArray: [ "hello" ] } | false | "hello" |
{ $isArray: [ [ "hello" ] ] } | true | [ "hello" ] |
Aggregation expressions accept a variable number of arguments. 聚合表达式接受数量可变的参数。These arguments are normally passed as an array. However, when the argument is a single value, you can simplify your code by passing the argument directly without wrapping it in an array.这些参数通常作为数组传递。但是,当参数是单个值时,可以通过直接传递参数而不将其封装在数组中来简化代码。
Example实例
Create the 创建warehouses
collection: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: [ ] }
] )
Check if the 检查instock
and the ordered
fields are arrays. If both fields are arrays, concatenate them: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" ] }