The earlier Query Operators lesson covered comparison, logical, and element/existence operators. This lesson covers two more categories: matching inside array fields, and matching text by pattern rather than exact value.
Matches a document whose array field contains every value listed, in any order — unlike a plain array match, which requires an exact match of the whole array.
db.products.find({ tags: { $all: ['electronics', 'sale'] } })
// Matches a document whose tags array contains BOTH 'electronics' and 'sale',
// regardless of order or other tags also presentNeeded when an array holds objects, and a single element must satisfy several conditions together — without it, conditions could each match a different element.
// A product with a reviews array: [{ rating: 5, verified: true }, { rating: 2, verified: false }]
// WITHOUT $elemMatch — matches if ANY review has rating 5 AND ANY review is verified,
// even if it's not the SAME review
db.products.find({ 'reviews.rating': 5, 'reviews.verified': true })
// WITH $elemMatch — requires one single review meeting both conditions
db.products.find({
reviews: { $elemMatch: { rating: 5, verified: true } }
})db.products.find({ tags: { $size: 3 } })
// Matches only documents whose tags array has exactly 3 elements$size has no range version
$size only matches an exact length — there's no built-in $size: { $gt: 3 } for "more than 3." A common workaround is a separate stored count field, kept in sync when the array changes.
Matches a string field against a regular expression, similar to the pattern matching from the earlier JavaScript course.
// Names starting with "Jo" (case-sensitive)
db.users.find({ name: { $regex: /^Jo/ } })
// Case-insensitive, matching anywhere in the string
db.users.find({ name: { $regex: /smith/i } })
// Alternative syntax, useful when the pattern is a variable
db.users.find({ name: { $regex: '^Jo', $options: 'i' } })A performance note
An unanchored $regex (no ^ at the start) can't use a text index efficiently and scans every document — fine on a small collection, worth watching on a large one. A dedicated text index (covered in the Specialized Indexes lesson) handles large-scale text search better.
| Operator | Matches |
|---|---|
| $all | An array containing every listed value |
| $elemMatch | One array element satisfying multiple conditions together |
| $size | An array with an exact number of elements |
| $regex | A string matching a pattern |