Docs HomeMongoDB Manual

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

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

See also: 另请参阅: