Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 70 ยท Query operators

Array Query Operators

Query MongoDB arrays with $all, $size and $elemMatch. Learn why two conditions can match different array elements and how $elemMatch fixes it.

Arrays are one of the best features of the document model. A post carries its tags, an order carries its items, a student carries a list of scores, all inside one document. Querying them is a little different from querying plain fields, because every condition can be satisfied by any element of the array, and two different conditions can be satisfied by two different elements. That second rule is behind the most common array-query bug in MongoDB.

You already know the basics from Querying Nested Fields and Arrays: { tags: "bread" } matches arrays that contain "bread", and "items.sku" reaches into an array of subdocuments. This lesson adds the three dedicated array operators: $all, $size and $elemMatch. As in the other lessons, plain code blocks show real mongosh commands that cannot run here, and the TryIts run on the site's practice engine, a small JavaScript matcher that follows MongoDB's rules for these operators. It is a stand-in, so it has no indexes or performance behavior.

The array operators

$all The array holds every listed value.
$size The array has exactly n elements.
$elemMatch One single element meets all conditions.
$in The array holds at least one listed value.
1 / 2

Contains, all, any and exact

Say a post document looks like { title: "Starter basics", tags: ["bread", "baking", "starter"] }. There are four different questions you can ask about tags, and each has its own syntax:

Question Filter
Contains "bread" { tags: "bread" }
Contains both "bread" and "baking" (any order) { tags: { $all: ["bread", "baking"] } }
Contains at least one of them { tags: { $in: ["bread", "baking"] } }
Is exactly this array, in this order { tags: ["bread", "baking", "starter"] }

$all is the "and" version of $in. It does not care about order or about extra elements. The exact-match form is far stricter: it needs the same elements, the same order and the same length, so ["baking", "bread", "starter"] does not match. Most of the time you want $all or a simple "contains", not the exact form.

$size matches arrays with an exact length, such as { tags: { $size: 3 } }. It does not accept a range, so { $size: { $gt: 2 } } is an error. To ask "at least three tags" in real MongoDB, test that the element at index 2 exists with { "tags.2": { $exists: true } }, or store a count field and index it. If you need ranges on array length often, keep a tagCount field up to date next to the array.

JS Contains, $all, $in, exact match and $size

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the two exact-match lines. Only "Weekend loaves" is stored as ["baking", "bread"], so that order finds it and the reverse order finds nothing, while $all matched both "Starter basics" and "Weekend loaves" no matter the order.

The classic bug: conditions that match different elements

Now an array of subdocuments. An order stores its line items, and you want orders that contain a pen with quantity at least 5. The natural first attempt uses dot notation:

JavaScript
db.orders.find({ "items.sku": "pen", "items.qty": { $gte: 5 } })

This does not mean "one item with sku pen and qty of at least 5". It means "some item has sku pen" AND "some item has qty of at least 5", and those can be two different items. An order with one pen (quantity 1) and one box of ink (quantity 5) matches, even though no single line is five pens. The same happens with plain values: { scores: { $gte: 80, $lt: 90 } } matches [95, 67], because 95 satisfies $gte: 80 and 67 satisfies $lt: 90.

$elemMatch fixes it by requiring one element to satisfy all the conditions inside it. Run the comparison to see the difference.

JS Different elements versus one element

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Dot notation wrongly returns Ben, whose pen line has quantity 1 and whose ink line has quantity 5. $elemMatch returns only Ana. The same split shows in the scores: Ben's [95, 67] sneaks into the flat query. Inside $elemMatch on an array of plain numbers you write operators directly ({ $gte: 80, $lt: 90 }); on an array of subdocuments you write a normal filter ({ sku: "pen", qty: { $gte: 5 } }).

The last line combines $all with $elemMatch to demand several lines that each satisfy their own conditions. Use it when "all of these things must exist, each with its own rules".

When one condition is enough

You do not need $elemMatch when you test only one condition on the elements. { items: { $elemMatch: { sku: "pen" } } } and { "items.sku": "pen" } return the same documents. Reach for $elemMatch as soon as two or more conditions must describe the same element. A good test: "if I read this filter aloud, do the words the same appear?" "An item that is a pen and has qty at least 5" says the same item.

A few related facts worth knowing:

  • Position: { "items.0.sku": "pen" } tests the first element only. Positions start at 0.
  • Negation: { tags: { $ne: "bread" } } matches arrays that contain no element equal to "bread". $nin works the same way across several values.
  • Empty and missing: an empty array contains nothing, so { tags: "bread" } skips it, and $all with an empty list matches no documents at all.
  • Indexes: an index on an array field is a multikey index that stores one entry per element, which is why queries like { tags: "bread" } can be fast. See Index Types.
  • Projection: to return only the matching element rather than the whole array, see Projection ($elemMatch and $slice projections), and for updating the matched element see Updating Arrays.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does { tags: { $all: ["bread", "baking"] } } match?

    $all requires every listed value to be present. Order and additional elements do not matter. Use $in for 'at least one' and the plain array form for an exact match.
  2. 2. An order has the items [{sku: pen, qty: 1}, {sku: ink, qty: 5}]. Does { 'items.sku': 'pen', 'items.qty': { $gte: 5 } } match it?

    Each dot-notation condition is checked independently against the whole array. Use $elemMatch to force both conditions onto one item.
  3. 3. Which filter finds arrays with at least three elements?

    $size only takes an exact number. Testing that index 2 exists works for 'at least three'. Many schemas also keep a separate count field for range queries.
  4. 4. When is $elemMatch NOT needed?

    With one condition there is nothing that could match different elements, so { 'items.sku': 'pen' } and $elemMatch give the same result.

Summary

  • A plain value matches an array that contains it; $all needs every listed value, $in needs at least one, and the exact array form needs the same elements in the same order.
  • $size matches an exact length only. For "at least n" test "field.n-1" with $exists, or keep a count field.
  • Conditions on an array field (or on array.field) can each be met by a different element.
  • $elemMatch forces all its conditions onto one element; on scalar arrays write the operators directly, on subdocument arrays write a filter.
  • Combine $all with $elemMatch to require several elements that each follow their own rule.
  • One condition on the elements needs no $elemMatch.

Next, search inside text with Text Matching and Regular Expressions.