Skip to the workspace
Pebellslearn by building
Query Operators  ›  Lesson

Array Operators: $all, $size, $elemMatch

$elemMatch 15 min$all requires an array to contain every listed value in any order, $size matches an exact length, and $elemMatch requires a single array element to satisfy all its conditions at once.

mongodb / Array Operators: $all, $size, $elemMatch

Explore each scene at your own pace.

01 · The rule

The rule

Array Operators: $all, $size, $elemMatch

Arrays are where MongoDB queries surprise people most. "A rating by Ben with 5 stars" sounds like one condition, but written the obvious way it matches a book where Ben gave 4 and someone else gave 5. Three operators give you precise control.

The rule

$all: every value present. $size: exact length. $elemMatch: one element passes everything.

The array fields in full:

title genres ratings
Dune sci-fi, classic asha 5, ben 4
Neuromancer sci-fi, cyberpunk asha 3
Emma classic, romance (empty array)
The Hobbit fantasy, classic, adventure ben 5, chen 2
Circe fantasy, myth (no field)
db.books.find({ genres: { $all: ["classic", "sci-fi"] } })   // Dune
db.books.find({ genres: { $size: 3 } })                      // The Hobbit
db.books.find({ ratings: { $elemMatch: { user: "ben", score: { $gte: 5 } } } })   // The Hobbit
  • $all needs every listed value somewhere in the array, in any order. Compare the exact match { genres: ["sci-fi", "classic"] }, which needs that exact array in that order.
  • $size matches an exact length only. It cannot take a range such as { $gt: 2 }.
  • $elemMatch requires one single element to satisfy all its conditions together.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.