$isArray (aggregation)

Definition

  • $isArray

New in version 3.2.

Determines if the operand is an array. Returns a boolean.

$isArray has the following syntax:

  1. { $isArray: [ <expression> ] }

Behavior

The <expression> can be any valid expression. For more information on expressions, seeExpressions.

ExampleResults
{ $isArray: [ "hello" ] }false
{ $isArray: [ [ "hello", "world" ] ] }true

Example

A collection named warehouses contains the following documents:

  1. { "_id" : 1, instock: [ "chocolate" ], ordered: [ "butter", "apples" ] }
  2. { "_id" : 2, instock: [ "apples", "pudding", "pie" ] }
  3. { "_id" : 3, instock: [ "pears", "pecans"], ordered: [ "cherries" ] }
  4. { "_id" : 4, instock: [ "ice cream" ], ordered: [ ] }

The following example checks if the instock and the orderedfields are arrays before concatenating the two:

  1. db.warehouses.aggregate([
  2. { $project:
  3. { items:
  4. { $cond:
  5. {
  6. if: { $and: [ { $isArray: "$instock" }, { $isArray: "$ordered" } ] },
  7. then: { $concatArrays: [ "$instock", "$ordered" ] },
  8. else: "One or more fields is not an array."
  9. }
  10. }
  11. }
  12. }
  13. ])
  1. { "_id" : 1, "items" : [ "chocolate", "butter", "apples" ] }
  2. { "_id" : 2, "items" : "One or more fields is not an array." }
  3. { "_id" : 3, "items" : [ "pears", "pecans", "cherries" ] }
  4. { "_id" : 4, "items" : [ "ice cream" ] }

See also

$cond, $concatArrays