$isArray (aggregation)

On this page本页内容

Definition定义

$isArray

New in version 3.2.版本3.2中的新功能。

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结果
{ $isArray: [ "hello" ] } false
{ $isArray: [ [ "hello", "world" ] ] } true

Example示例

A collection named warehouses contains the following documents:名为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: [ ] }

The following example checks if the instock and the ordered fields are arrays before concatenating the two:以下示例在连接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" ] }

See also参阅

$cond, $concatArrays