developer-roadmap icon indicating copy to clipboard operation
developer-roadmap copied to clipboard

Fix logical mistake in $elemMatch example in elem-match.md

Open manojpatra061 opened this issue 7 months ago • 0 comments

What this PR does

Corrects a logically incorrect MongoDB query example in elem-match.md.

Problem

The original example tries to match two different subject and score values inside a single $elemMatch clause. However, since object keys must be unique, only the last subject and score values are actually considered. This makes the query behave differently than intended.

Since we want to find all the students who have scored 80 or above in Math and 70 or above in English, the query can even match the documents with no "Math" subject at all in "grades" field.

Documents like this will be selected (which you don't want) 👉 "grades" : [ { subject: "Science", score: 80 }, { subject: "English", score: 75, } ]

Solution

Replaced the query with one that uses $and and two separate $elemMatch clauses:

  • One for finding a grade with subject "Math" and score ≥ 80
  • Another for finding a grade with subject "English" and score ≥ 70

This ensures that both conditions are checked across different elements in the array.

Why this matters

The original example doesn't throw an error, but it behaves incorrectly and could mislead developers trying to learn how $elemMatch works.

manojpatra061 avatar May 17 '25 05:05 manojpatra061