liveBook · Manning

$elemMatch operator

As explained in MongoDB 8.0 in Action, Third Edition

The $elemMatch operator selects array documents or elements for which a single array element satisfies multiple specified criteria.

$elemMatch selects documents where one array element satisfies multiple conditions simultaneously. This prevents separate criteria from being satisfied by different elements. section 4.8 section 4.9.3

Use the operator when:

  • A numeric array must contain one value greater than 300000 and less than 400000. section 4.8
  • An embedded-document array must contain one item matching several fields, such as business class with a price below 3000. section 4.9.3
  • Prefer direct array conditions for a single criterion; use $all for required values and $size for an exact element count. section 4.8

Match one account number within a range

db.customers.find({ accounts: { $elemMatch: { $gt: 300000, $lt: 400000 } } }) The query returns customers whose accounts array contains at least one number in the specified range, regardless of other array values. section 4.8

Match one embedded document

db.routes.find({ prices: { $elemMatch: { class: 'business', price: { $lt: 3000 } } } }) The query requires both conditions to hold within the same prices element. section 4.9.3

Listing 4.16 Using the $elemMatch operator
db.customers.find({
accounts: { $elemMatch: { $gt: 300000, $lt: 400000 } }
})

Inspect the complete numeric-array query using $elemMatch. section 4.8

db.routes.find({
  prices: {
    $elemMatch: {
      class: 'business',
      price: { $lt: 3000 }
    }
  }
})

Inspect the complete query that combines embedded-document fields within one array element. section 4.9.3

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains same-element matching with numeric and embedded-document queries, but does not address indexing or performance.
Examples
Demonstrates account-number ranges and route prices containing a business-class item below a threshold.
What you can do after
Apply it via MongoDB find queries to enforce multiple conditions on the same array element.
How it connects
Connects array queries with dot notation, embedded documents, $all, and $size.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.