🍃 MongoDB Tutorial

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)

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 $all if you just want to check that certain values are present, regardless of order or extra elements.
  • Expecting $size to accept a range — $size only matches an exact length; there's no $size: {$gt: 2}. If you need a range on array length, use aggregation's $expr with $size (the aggregation array function, not this query operator) instead.
  • $elemMatch conditions accidentally matching across different elements — leaving out $elemMatch when you have multiple conditions lets them each match a different array element; add $elemMatch whenever both conditions must hold on the same element.

Key Takeaways

  • $all checks that every listed value is present somewhere in the array.
  • $size matches an exact array length only — no ranges.
  • $elemMatch is essential once you need more than one condition to hold on the same array element.