Database Manual / Reference / Query Language / Expressions

$isArray (expression operator)(表达式运算符)

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.有关表达式的详细信息,请参阅表达式

Example示例Results结果Notes备注
{ $isArray: "hello" }false"hello" is a string, passed as a string.是一个字符串,作为字符串传递。
{ $isArray: [ "hello" ] }false"hello" is a string, passed as part of an argument array.是一个字符串,作为参数数组的一部分传递。
{ $isArray: [ [ "hello" ] ] }true[ "hello" ] is an array, passed as part of an argument array.是一个数组,作为参数数组的一部分传递。

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:检查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" ] }