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
- Find restaurants that have at least one grade with a
scorebelow 5. easy restaurants - Find restaurants that have a single grade entry which is BOTH grade
AAND scored below 6. medium restaurants - Find restaurants whose SECOND grade entry is grade
Awith ascoreof 9. medium restaurants - Find restaurants with exactly 3 grade entries. easy restaurants
- Find movies that are tagged with BOTH
DramaandThrillergenres, in any order. medium movies - Find restaurants where EVERY grade scored above 5. hard restaurants
- The
address.coordarray is[longitude, latitude]. Find restaurants whose latitude is above 40.75. medium restaurants - Find products tagged
wireless. easy products - Find movies with an empty
castarray. medium movies - Find orders containing at least one line item with
qtyof 3 or more. medium orders - Find restaurants that have received at least one
Agrade AND at least oneCgrade. hard restaurants - Find restaurants that have at least one
Agrade but have NEVER received aC. 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?
{ 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?
"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?
$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