Definition定义
$isArrayDetermines if the operand is an array. Returns a boolean.确定操作数是否为数组。返回一个布尔值。$isArrayhas 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" ] |
Note
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 a collection named 使用以下文档创建一个名为warehouses with the following documents: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" ] }