Navigation
This version of the documentation is archived and no longer supported.

$elemMatch (query)

Definition

$elemMatch

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }

If you specify only a single <query> condition in the $elemMatch expression, you do not need to use $elemMatch.

Behavior

Examples

Element Match

Given the following documents in the scores collection:

{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }

The following query matches only those documents where the results array contains at least one element that is both greater than or equal to 80 and is less than 85.

db.scores.find(
   { results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)

The query returns the following document since the element 82 is both greater than or equal to 80 and is less than 85

{ "_id" : 1, "results" : [ 82, 85, 88 ] }

For more information on specifying multiple criteria on array elements, see Specify Multiple Conditions for Array Elements.

Array of Embedded Documents

Given the following documents in the survey collection:

{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }

The following query matches only those documents where the results array contains at least one element with both product equal to "xyz" and score greater than or equal to 8.

db.survey.find(
   { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)

Specifically, the query matches the following document:

{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] }

Single Query Condition

If you specify a single query predicate in the $elemMatch expression, $elemMatch is not necessary.

For example, consider the following example where $elemMatch specifies only a single query predicate { product: "xyz" }:

db.survey.find(
   { results: { $elemMatch: { product: "xyz" } } }
)

Since the $elemMatch only specifies a single condition, the $elemMatch expression is not necessary, and instead you can use the following query:

db.survey.find(
   { "results.product": "xyz" }
)

Additional Examples

For additional examples in querying arrays, see:

For additional examples in querying, see:

←   $all $size  →