$isArray (Check If Value Is Array)
Last updated: 2026-10-09
$isArray (Check If Value Is Array)
$isArray returns a boolean indicating whether an expression resolves to an array. It is frequently used inside $cond for type branching: when a field may be either a scalar or an array, check first and then choose a processing path. It also guards operators like $size or $map that only accept arrays, preventing errors. It is the type guard of aggregation expressions and can be combined with $type for precise BSON type checks. A missing field yields false rather than an error.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $isArray: <expression> }
⚙️ Parameters
| expression | Any expression whose result is checked for array type. |
|---|
Returns:A boolean: true when the result is an array, otherwise false
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $isArray: tags may be a string or an array, count both
db.products.aggregate([
{ $project: {
tagCount: { $cond: { if: { $isArray: '$tags' }, then: { $size: '$tags' }, else: 1 } }
} }
])
Output:
{ '_id': 1, 'tagCount': 3 }
{ '_id': 2, 'tagCount': 1 }
📌 Notes
- A missing field yields false, not an error
- Nested arrays (arrays inside arrays) count as arrays, so $isArray returns true
- Combine with $cond/$switch for type dispatch and to avoid calling $size on non-arrays
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat does $isArray return when the field is missing?
AIt returns false without throwing, making it safe for guards.
QCan $isArray tell a string from an array?
AYes — strings return false; only the BSON Array type returns true.
QHow do I use it with $cond?
APut $isArray in the if position of $cond and write two branches in then/else.