$elemMatch — MongoDB Technical Interview Questions & Answers

Matching an array element against multiple conditions.

$elemMatch

  • Simple meaning: $elemMatch says “one array element must satisfy all these conditions”, not two different elements sharing the conditions.
  • How to use: db.scores.find({ results: { $elemMatch: { subject: "Maths", marks: { $gte: 40 } } } }).
  • Without $elemMatch, { "results.subject": "Maths", "results.marks": { $gte: 40 } } can match Maths on one row and 40 on another.
  • Try this: two nested objects in an array, then $elemMatch vs dotted fields.
  • Interview tip: Array of objects + two conditions on the same element → $elemMatch.

Technical Interview Tip: Array of objects: $elemMatch for AND on one element.

Code Examples for $elemMatch

$elemMatch — working example

db.users.find({
  scores: { $elemMatch: { subject: "Math", marks: { $gte: 80 } } }
})

// Example document shape:
// { name: "Ada", scores: [ { subject: "Math", marks: 92 }, { subject: "Eng", marks: 70 } ] }

$elemMatch requires a single array element to satisfy all nested conditions.

How to Explain $elemMatch to an Interviewer

When $elemMatch?

When several conditions must hold on the same array element