MongoDB $isArray Operator

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 vegiie and name fields are array or not using $isArray operator. Here, the value of checkResult1 is true because vegiie 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: "$vegiie"},
... 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]]}}}])

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.