$elemMatch (query)

See also

$elemMatch (projection)

Definition

  • $elemMatch
  • The $elemMatch operator matches documents thatcontain an array field with at least one element that matches all thespecified query criteria.
  1. { <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:

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

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

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

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

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

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

Array of Embedded Documents

Given the following documents in the survey collection:

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

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

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

Specifically, the query matches the following document:

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

Single Query Condition

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

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

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

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

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

Additional Examples

For additional examples in querying arrays, see:

For additional examples in querying, see:

See also

db.collection.find()