Fix This Page
Navigation

$isArray (aggregation)

On this page

Definition

$isArray

New in version 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. 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:

{ "_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:

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