The Wayback Machine - https://web.archive.org/web/20250228133343/https://www.geeksforgeeks.org/mongodb-isarray-operator/
Open In App

MongoDB – $isArray Operator

Last Updated : 10 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In MongoDB, arrays are used to store lists of information such as product categories or tags. The $isArray operator is a tool that helps us to check if a specific field contains an array. This is important for managing data effectively especially when dealing with mixed data types in our collections.

In this article, We will learn about the MongoDB $isArray Operator by understanding variou examples, their working and so on.

Introduction to MongoDB $isArray

In MongoDB, arrays are commonly used to store lists of data, such as lists of products, tags or items in stock. However, sometimes we need to verify whether a specific field contains an array or another data type like a string or number.

The $isArray operator in MongoDB is designed for the purpose which check whether the provided expression evaluates to an array and returns a boolean value (true or false).

Syntax:

{ $isArray: [ <expression> ] }
  • Expression: This can be any valid MongoDB expression, such as a field or a computed value.

How $isArray Works?

The $isArray operator is used in aggregation pipelines where determining whether a field is an array is necessary for further processing.

It is particularly useful when we have a collection where some fields can hold either an array or a scalar value, and we want to conditionally apply operations based on the field type.

Examples of MongoDB $isArray Operator

Let’s consider below collection called products on which we will perform the various examples and so on.

db.products.insertMany([
{ _id: 1, name: "Laptop", categories: ["Electronics", "Computers"], stock: 30 },
{ _id: 2, name: "Phone", categories: "Electronics", stock: 100 },
{ _id: 3, name: "Shirt", categories: ["Apparel", "Men"], stock: 50 },
{ _id: 4, name: "Shoes", categories: ["Apparel", "Women"], stock: 25 },
{ _id: 5, name: "Watch", stock: 15 }
])

Example 1: Basic $isArray Usage

We’ll start by checking whether the categories field is an array for each product.

db.products.aggregate([
{
$project: {
name: 1,
isCategoriesArray: { $isArray: "$categories" }
}
}
])

Output:

[
{ "_id": 1, "name": "Laptop", "isCategoriesArray": true },
{ "_id": 2, "name": "Phone", "isCategoriesArray": false },
{ "_id": 3, "name": "Shirt", "isCategoriesArray": true },
{ "_id": 4, "name": "Shoes", "isCategoriesArray": true },
{ "_id": 5, "name": "Watch", "isCategoriesArray": false }
]

Explanation:

The isCategoriesArray field checks whether the categories field is an array. For Laptop, Shirt, and Shoes, this field is true, while for Phone and Watch, it is false because either the value is a string or the field does not exist.

Example 2: Conditionally Applying Logic Based on Array Check

In this example, we’ll check if categories is an array and concatenate the array with a new value only if it is an array.

Query:

db.products.aggregate([
{
$project: {
name: 1,
updatedCategories: {
$cond: {
if: { $isArray: "$categories" },
then: { $concatArrays: [ "$categories", [ "Discounted" ] ] },
else: "Not an array"
}
}
}
}
])

Output:

[
{ "_id": 1, "name": "Laptop", "updatedCategories": [ "Electronics", "Computers", "Discounted" ] },
{ "_id": 2, "name": "Phone", "updatedCategories": "Not an array" },
{ "_id": 3, "name": "Shirt", "updatedCategories": [ "Apparel", "Men", "Discounted" ] },
{ "_id": 4, "name": "Shoes", "updatedCategories": [ "Apparel", "Women", "Discounted" ] },
{ "_id": 5, "name": "Watch", "updatedCategories": "Not an array" }
]

Explanation:

This query checks if categories is an array. If it is, the operator concatenates the existing array with ["Discounted"]. If it’s not an array (like for Phone or Watch), it returns "Not an array".

Example 3: Count Elements in an Array

In this example, we’ll use $isArray to check if categories is an array and then count how many items are in the array, if it exists.

Query:

db.products.aggregate([
{
$project: {
name: 1,
categoryCount: {
$cond: {
if: { $isArray: "$categories" },
then: { $size: "$categories" },
else: 0
}
}
}
}
])

Output:

[
{ "_id": 1, "name": "Laptop", "categoryCount": 2 },
{ "_id": 2, "name": "Phone", "categoryCount": 0 },
{ "_id": 3, "name": "Shirt", "categoryCount": 2 },
{ "_id": 4, "name": "Shoes", "categoryCount": 2 },
{ "_id": 5, "name": "Watch", "categoryCount": 0 }
]

Explanation:

This query first checks if categories is an array. If true, it counts the number of elements in the array using $size. If not, it assigns 0.

Example 4: Filtering Documents Where a Field Is an Array

Now, let’s filter out only the documents where the categories field is an array.

Query:

db.products.aggregate([
{
$match: {
$expr: { $isArray: "$categories" }
}
}
])

Output:

[
{ "_id": 1, "name": "Laptop", "categories": [ "Electronics", "Computers" ], "stock": 30 },
{ "_id": 3, "name": "Shirt", "categories": [ "Apparel", "Men" ], "stock": 50 },
{ "_id": 4, "name": "Shoes", "categories": [ "Apparel", "Women" ], "stock": 25 }
]

Explanation:

Here, we are using $match with $expr to filter documents where the categories field is an array. Only documents for Laptop, Shirt, and Shoes are returned.

Conclusion

Overall, using the $isArray operator in MongoDB significantly enhances data processing capabilities, allowing developers to conditionally manipulate data based on its type. By incorporating this operator into queries, users can improve query efficiency and ensure that their applications handle diverse data types seamlessly, resulting in more robust data management strategies.

FAQs

What is the purpose of the $isArray operator in MongoDB?

The $isArray operator is used to determine whether a given expression evaluates to an array. It returns true if the expression is an array and false otherwise, making it useful for validating data types in documents.

Can $isArray be used outside of aggregation pipelines?

No, the $isArray operator is specifically designed for use within aggregation pipelines in MongoDB. It helps in transforming and analyzing data based on the type of fields.

What happens if the field being checked does not exist in a document?

If the field being checked does not exist in a document, $isArray will return false, as the absence of the field means it cannot be an array.



Next Article

Similar Reads

three90RightbarBannerImg