Skip to main content

When do you need to use $elemMatch?

$elemMatch is needed when several conditions need to be checked against the same array element at once.

An example without $elemMatch (doesn't work):

js
db.users.find({ "scores.value": { $gt: 50 }, "scores.type": "math" })

MongoDB might find one element with value > 50 and a different element with type = "math", meaning the conditions matched different array elements, which is wrong.

The correct query with $elemMatch:

js
db.users.find({ scores: { $elemMatch: { value: { $gt: 50 }, type: "math" } } })

Now both conditions apply to the same element of the scores array.

The summary for a junior developer: $elemMatch is used when you need to find an array element that satisfies several conditions at once, not one that's just present in the array.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.