On this page
$isArray (aggregation)
在本页面
Definition
$isArray
- 3.2 版中的新功能。
确定操作数是否为数组。返回一个布尔值。
$isArray具有以下语法:
{ $isArray: [ <expression> ] }
Behavior
<expression>
可以是任何有效的expression。有关表达式的更多信息,请参见Expressions。
Example | Results |
---|---|
{ $isArray: [ "hello" ] } |
false |
{ $isArray: [ [ "hello", "world" ] ] } |
true |
Example
名为warehouses
的集合包含以下文档:
{ "_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" ] }
See also