Open In App

MongoDB – $isArray Operator

MongoDB $isArray operator is a type of array expression operator used in the aggregation pipeline stages. This operator is used to check if the specified expression is an array or not.

This operator will return true if the specified expression is an array. Otherwise, it will return false.



Syntax

{ $isArray: [ <expression> ] }

MongoDB $isArray operator 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.



Example 1: 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. 

Query:

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

Output:

Example 2: 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]).

Query:

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

Output:

Key Takeaways About $isArray Operator

Article Tags :