- Reference >
- Operators >
- Query and Projection Operators >
- Query Operator Array >
- $elemMatch (query)
$elemMatch (query)¶
Definition¶
- $elemMatch¶
New in version 1.4.
The $elemMatch operator matches documents in a collection that contain an array field with at least one embedded document or value that matches all the specified criteria.
Behavior¶
Changed in version 2.6.
The $where query operator will not work inside an $elemMatch query applied to nested documents.
Examples¶
Consider the following query:
db.grades.find( { records: { $elemMatch: { student: "Jane", grade: { $gt: 85 } } } } );
This example returns all documents in the grades collection where any element in the records array satisfies all of the conditions in the $elemMatch expression. This example returns all documents in the grades collection where the records array contains at least one element with both student equal to Jane and grade greater than 85.
Because matching arrays must have at least one element that matches all specified criteria, the document below would match the query because the { student: "Jane", grade: 90 } embedded document matches all the specified criteria:
{ records: [ { student: "Jane", grade: 90 }, { student: "Jane", grade: 78 } ] }
However, the following document would not match the query because no embedded document meets the specified criteria:
{ records: [ { student: "Jane", grade: 78 }, { student: "Bob", grade: 90 } ] }