Introduction to MongoDB $isArray Operator
The MongoDB $isArray
operator is used to determine if an expression is an array. If the expression is an array, it returns true
, otherwise it returns false
. This operator is typically used in the aggregation pipeline.
Syntax
The syntax for the $isArray
operator is as follows:
{ $isArray: <expression> }
Here, <expression>
represents the expression to be evaluated.
Use Cases
The $isArray
operator is often used in the aggregation pipeline to determine if a field is an array, and then perform the corresponding aggregation operation. For example, the $isArray
operator can be used in conjunction with the $cond
operator for conditional aggregation, to perform different aggregation operations based on whether a field is an array or not.
Example
The following aggregation pipeline uses the $isArray
operator to filter documents in the orders
collection where the orderItems
field is an array, and calculates the length of the orderItems
array:
db.orders.aggregate([
{
$match: {
$expr: {
$isArray: "$orderItems"
}
}
},
{
$project: {
_id: 0,
orderNumber: 1,
orderItemsCount: {
$size: "$orderItems"
}
}
}
])
Assuming the orders
collection contains the following documents:
{
orderNumber: "2022030101",
orderItems: [
{ product: "A", quantity: 2 },
{ product: "B", quantity: 1 }
]
}
{
orderNumber: "2022030102",
orderItems: { product: "C", quantity: 3 }
}
{
orderNumber: "2022030103",
orderItems: [
{ product: "D", quantity: 1 },
{ product: "E", quantity: 2 },
{ product: "F", quantity: 1 }
]
}
After running the above aggregation pipeline, the following results can be obtained:
{
"orderNumber": "2022030101",
"orderItemsCount": 2
}
{
"orderNumber": "2022030103",
"orderItemsCount": 3
}
Conclusion
The $isArray
operator is a very useful operator that can be used to determine if a field is an array. This operator can be used in various stages of the aggregation pipeline, such as in the $project
stage, to process fields as needed. Using the $isArray
operator can make the aggregation pipeline more flexible and increase the readability and maintainability of the code.