MongoDB regex and pattern matching
$regex β starts with, ends with, contains, case-insensitive. Β· 9 practice questions Β· Cheat sheet β
$regex matches strings against a pattern, so a MongoDB regex query for "starts with", "ends with" or "contains" is a one-liner: { name: /^B/ }, { name: /e$/ }, { name: /Bar/ }. You can write the pattern as a JavaScript literal or as { $regex: "^B", $options: "i" }, where i makes it case-insensitive. The anchors ^ and $ plus the wildcard . cover most needs; everything else is ordinary regular-expression syntax.
Two practical notes. Characters like ., ( and + mean something in a pattern, so escape them with a backslash when you mean them literally. And only patterns anchored at the start (^...) can use an index; a leading wildcard scans every document, which is fine for practice collections and painful at scale.
MongoDB regex query practice questions
- Find restaurants whose
namestarts withB. easy restaurants - Find restaurants whose
nameends with the lettere. easy restaurants - Find restaurants whose
namecontainsBaranywhere. easy restaurants - Find restaurants whose
cuisinestarts with the letterC. Returnnameandcuisinewithout_id. medium restaurants - Find restaurants whose
address.zipcodestarts with10. medium restaurants - Find restaurants whose
namecontainscafe, ignoring case. medium restaurants - Find movies whose
titlecontains the wordthe, ignoring case. Returntitleonly, without_id. medium movies - Find restaurants whose
address.streetends withAveorBlvd. hard restaurants - Find restaurants whose
cuisinestarts with any of the letters I, J or K. hard restaurants
Each question is answered in a live mongo-shell editor on this page; the result is checked against a reference solution.
$regex cheat sheet: anchors, options, escaping
Two equivalent forms
db.restaurants.find({ name: { $regex: "^B" } })
db.restaurants.find({ name: /^B/ })
The three anchors you need
| Goal | Pattern |
|---|---|
starts with Bro | /^Bro/ |
ends with Bar | /Bar$/ |
contains Bar anywhere | /Bar/ |
| case-insensitive contains | /bar/i or { $regex: "bar", $options: "i" } |
| starts with any of a set | /^[BCD]/ |
Escaping
Dots, parens and $ are regex metacharacters:
{ email: /\.com$/ } // literal dot, then "com" at the end
Gotchas
- Only
^-anchored, case-sensitive regexes can use an index./foo/i
scans the whole collection.
- Regex works on strings only β it will not match a number field.
Common questions
How do I do a "starts with" query in MongoDB?
{ name: /^Bar/ } or { name: { $regex: "^Bar" } }. Add the i option for case-insensitive matching: /^bar/i. Anchored prefixes can use an index on the field; unanchored patterns cannot.How do I make a MongoDB regex case-insensitive?
i flag: { cuisine: /italian/i } or { cuisine: { $regex: "italian", $options: "i" } }. For exact case-insensitive equality on many queries, a case-insensitive collation on the collection or index is the faster long-term option.Can I use $regex on a number field?
$regex only matches string values; documents whose field holds a number are simply skipped. To pattern-match numbers, convert them first in an aggregation with $toString, or store a string copy of the value alongside the number.Continue:β Element & TypeSort, Limit & Skip β
MongoDB topics:Finding & ProjectionComparison OperatorsLogical OperatorsElement & TypeSort, Limit & SkipArray QueriesEmbedded DocumentsAggregation BasicsGrouping & Accumulators$unwind & Array PipelinesJoins & Advanced StagesFull cheat sheet