MongoDB - $isArray Operator
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 various examples, their working and so on.
What is the MongoDB $isArray Operator?
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
). The $isArray
operator in MongoDB is used to determine if a given field or expression is an array. It returns a boolean value:
true
if the expression evaluates to an array.false
if the expression does not evaluate to an array.
Syntax:
{ $isArray: [ <expression> ] }
- Expression: This can be any valid MongoDB expression, such as a field or a computed value.
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.
When to Use the $isArray
Operator?
The $isArray
operator is useful in scenarios where:
- We have fields in our documents that could be either arrays or non-array types.
- We want to perform operations (such as counting array elements, adding items to an array, or performing conditional updates) based on whether a field is an array or not.
- By checking if a field is an array, we can write more efficient and dynamic queries that adapt to different data types in your collection.
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
Suppose we have a collection of products, and each product can have a categories
field that may either be an array or a string. We want to check if the categories
field is an array for each product.
Query:
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. If it’s not an array, we will return "Not 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
Let’s say we want to count how many categories each product has. We can use $isArray
to check if categories
is an array and then apply the $size
operator to count the number of elements.
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 Checks if
categories
is an array. - If it is, it counts the number of items using the
$size
operator. - If it’s not an array, it assigns
0
tocategoryCount
.
Example 4: Filtering Documents Where a Field Is an Array
If we need to filter out only those documents where the categories
field is an array, you can use $isArray
in combination with $match
.
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. As a result, the query returns only the documents for Laptop, Shirt, and Shoes.
Best Practices for Using the $isArray
Operator
- Use
$isArray
with Conditional Operations: Use$isArray
within the$cond
operator or other conditional operators to perform different operations based on the data type. - Efficient Data Handling: When working with collections where fields can vary in type,
$isArray
helps ensure that only the appropriate operations are applied to array fields. - Combine with Other Operators: Use
$isArray
with operators like$size
,$concatArrays
, or$push
to manipulate array fields dynamicall
Conclusion
The MongoDB $isArray
operator is a powerful tool that allows you to check whether a specific field in your document is an array. It helps us manage and manipulate data efficiently, especially when working with collections that contain mixed data types. By incorporating $isArray
in our aggregation pipelines, we can write more flexible and dynamic queries that improve data processing and query efficiency.