Problem Statement
How do you query array fields in MongoDB? Explain $elemMatch with an example.
Explanation
MongoDB provides several operators for querying array fields. The simplest way is to match an array that contains a specific value. For example, to find users with JavaScript skill, you query skills colon JavaScript.
For more complex array queries with multiple conditions on array elements, use the dollar elemMatch operator. This ensures all conditions are met by the same array element, not different elements.
For example, if you have an array of grade objects and want to find students who scored above 80 in Math, dollar elemMatch ensures both the subject and score conditions apply to the same grade object. Without dollar elemMatch, MongoDB might match a document where one element has subject Math and a different element has score above 80.
Other useful array operators include dollar all to match arrays containing all specified values, dollar size to match arrays of a specific length, and dollar slice for array projections.
Code Solution
SolutionRead Only
// Simple array match
db.users.find({ skills: "JavaScript" })
// $elemMatch - multiple conditions on same element
db.students.find({
grades: {
$elemMatch: {
subject: "Math",
score: { $gt: 80 }
}
}
})
// Without $elemMatch (may match wrong docs)
db.students.find({
"grades.subject": "Math",
"grades.score": { $gt: 80 }
})Practice Sets
This question appears in the following practice sets:
