$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
