MongoDB Array Query Operators: $all, $size, $elemMatch
Learn how to query MongoDB array fields with $all (contains all values), $size (exact array length), and $elemMatch (matching multiple conditions on one element).
MongoDB Array Query Operators
Array operators are designed specifically for querying fields that store arrays.
| Operator | Description |
|---|---|
$all |
Matches arrays that contain all of the specified values |
$size |
Matches arrays with an exact number of elements |
$elemMatch |
Matches if at least one array element satisfies all listed conditions |
$all
db.employees.find({ lang: { $all: ['Marathi', 'English'] } })
// matches documents where lang contains BOTH Marathi and English (order doesn't matter)
db.employees.find({ deptwork: { $all: [6, 7] } })
$size
Matches only on the array's length — it can't be combined with a range (there's no $size: { $gt: 2 }).
db.employees.find({ deptwork: { $size: 2 } })
// deptwork array has exactly 2 elements
db.employees.find({ lang: { $size: 4 } })
$elemMatch
Without $elemMatch, multiple conditions on an array field can match across different elements. $elemMatch forces all conditions to be satisfied by the same single element.
db.employees.find({ deptwork: { $elemMatch: { $lt: 3 } } })
// at least one element in deptwork is less than 3
db.employees.find({ deptwork: { $elemMatch: { $gte: 2, $lte: 4 } } })
// at least one element is between 2 and 4 (inclusive)
Advertisement728 x 90
Common Errors & Troubleshooting
{ tags: ['sql', 'nosql'] }doesn't match an array containing extra tags — a plain equality match against an array requires the array to contain exactly those elements in that order. Use$allif you just want to check that certain values are present, regardless of order or extra elements.- Expecting
$sizeto accept a range —$sizeonly matches an exact length; there's no$size: {$gt: 2}. If you need a range on array length, use aggregation's$exprwith$size(the aggregation array function, not this query operator) instead. $elemMatchconditions accidentally matching across different elements — leaving out$elemMatchwhen you have multiple conditions lets them each match a different array element; add$elemMatchwhenever both conditions must hold on the same element.
Key Takeaways
$allchecks that every listed value is present somewhere in the array.$sizematches an exact array length only — no ranges.$elemMatchis essential once you need more than one condition to hold on the same array element.
Advertisement320 x 100