πŸƒDBQuestpractice MongoDB queries
0 / 110

MongoDB array queries: $elemMatch, $all, $size

$all, $size, $elemMatch, positional dot paths.  Β·  12 practice questions  Β·  Cheat sheet ↓

Arrays are where MongoDB queries stop behaving like SQL. A plain { genres: "Drama" } matches if any element equals Drama, { genres: ["Drama", "Thriller"] } needs the exact array, $all wants every listed value present in any order, and $size matches an exact length. "grades.0.grade" reaches the first element by position, and "grades.grade" reaches that field in every element.

To query an array of objects correctly you need $elemMatch. { "grades.grade": "A", "grades.score": { $lt: 6 } } is satisfied by one element with the A and a different element with the low score. { grades: { $elemMatch: { grade: "A", score: { $lt: 6 } } } } demands a single element with both. That gap is the number-one array bug, and the $elemMatch examples here exist to make the difference stick.

MongoDB array query practice questions

  1. Find restaurants that have at least one grade with a score below 5. easy restaurants
  2. Find restaurants that have a single grade entry which is BOTH grade A AND scored below 6. medium restaurants
  3. Find restaurants whose SECOND grade entry is grade A with a score of 9. medium restaurants
  4. Find restaurants with exactly 3 grade entries. easy restaurants
  5. Find movies that are tagged with BOTH Drama and Thriller genres, in any order. medium movies
  6. Find restaurants where EVERY grade scored above 5. hard restaurants
  7. The address.coord array is [longitude, latitude]. Find restaurants whose latitude is above 40.75. medium restaurants
  8. Find products tagged wireless. easy products
  9. Find movies with an empty cast array. medium movies
  10. Find orders containing at least one line item with qty of 3 or more. medium orders
  11. Find restaurants that have received at least one A grade AND at least one C grade. hard restaurants
  12. Find restaurants that have at least one A grade but have NEVER received a C. hard restaurants

Each question is answered in a live mongo-shell editor on this page; the result is checked against a reference solution.

$elemMatch, $all and $size cheat sheet

Matching against an array field

{ genres: "Drama" }              // array CONTAINS "Drama"
{ genres: ["Drama","Thriller"] } // array EQUALS exactly this, in this order
{ genres: { $all: ["Drama","Thriller"] } }  // contains both, any order
{ genres: { $size: 3 } }         // exactly 3 elements

Positional access

{ "grades.0.grade": "A" }        // first element's grade
{ "address.coord.1": { $gt: 40.75 } }  // second number in the array

$elemMatch – the important one

// βœ— one grade has A, ANOTHER has score < 6 – both conditions, different elements
{ "grades.grade": "A", "grades.score": { $lt: 6 } }

// βœ“ ONE SINGLE element has both
{ grades: { $elemMatch: { grade: "A", score: { $lt: 6 } } } }

Without $elemMatch, multiple conditions on the same array can be satisfied

by different elements. This is the #1 array bug.

"All elements satisfy X"

There is no $allMatch. You invert it:

// every grade scored above 5  ==  no grade scored 5 or less
{ grades: { $not: { $elemMatch: { score: { $lte: 5 } } } } }

Common questions

What does $elemMatch do?

It requires one array element to satisfy all the conditions at once. { grades: { $elemMatch: { grade: "A", score: { $lt: 6 } } } } finds a single grade that is both an A and below 6. Without it, each condition may be met by a different element.

Why do two conditions on an array match different elements?

Dot-notation conditions are evaluated independently: "grades.grade": "A" is true if any element is an A, and "grades.score": { $lt: 6 } is true if any element scores under 6. Nothing ties them to the same element. $elemMatch does exactly that.

How do I match documents where every array element satisfies a condition?

There is no $allMatch; invert it instead. "Every grade above 5" is "no grade of 5 or less": { grades: { $not: { $elemMatch: { score: { $lte: 5 } } } } }. Add grades: { $exists: true, $ne: [] } if empty arrays should not count.

Continue:← Sort, Limit & SkipEmbedded Documents β†’

MongoDB topics:Finding & ProjectionComparison OperatorsLogical OperatorsElement & TypePattern MatchingSort, Limit & SkipEmbedded DocumentsAggregation BasicsGrouping & Accumulators$unwind & Array PipelinesJoins & Advanced StagesFull cheat sheet