Open In App

MongoDB $isArray Operator

Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $isArray operator is one of them. This operator is used to check if the specified expression is an array or not. Or in other words, this operator is used to check if the operand is an array. This operator will return true if the specified expression is an array. Otherwise, it will return false.

Syntax: 

{ $isArray: [ <expression> ] }

Here, the expression must be a valid expression.

 Examples:

In the following examples, we are working with:

Database: GeeksforGeeks

Collection: arrayExample

Document: three documents that contain the details in the form of field-value pairs.

Using $isArray Operator:

In this example, we are going to check if the values of veggie and name fields are array or not using $isArray operator. Here, the value of checkResult1 is true because veggie is an array and the value of checkResult2 is false because name is not an array. 

db.arrayExample.aggregate([
... {$match: {name: "Bongo"}},
... {$project: {
... checkResult1: {$isArray: "$veggie"},
... checkResult2: {$isArray: "$name"}}}])

Using $isArray Operator in the Embedded Document:

In this example, In this example, we are going to check if the value of favGame.indoorGames field is an array or not using $isArray operator. Here, the value of checkResult1 is true because favGame.indoorGames is an array and the value of checkResult2 is also true because the given expression in the $isArray operator is an array(i.e., [1, 3, 4]).

db.arrayExample.aggregate([
... {$match: {name: "Piku"}},
... {$project: {
... checkResult1: {$isArray: "$favGame.indoorGames"},
... checkResult2: {$isArray: [[1, 3, 4]]}}}])


Last Updated : 07 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads