$regex (Regex Match)
Last updated: 2026-10-09
$regex (Regex Match)
$regex matches string fields with a regular expression. `{ name: { $regex: '^A' } }` matches names starting with A. Options: i case-insensitive, m multiline, x ignore whitespace. Without an index a $regex query scans the whole collection; only anchored prefixes (^) with case sensitivity can leverage a normal index.
| Category | Element & Evaluation |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ <field>: { $regex: <pattern>, $options: '<options>' } }
⚙️ Parameters
| field | The document field to match. |
|---|---|
| regex | A PCRE-style regular expression pattern. |
| options | Optional: i case-insensitive, m multiline, x ignore whitespace, etc. |
Returns:Cursor of matching documents
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $regex: names starting with A (case-sensitive)
db.users.find({ name: { $regex: '^A' } })
// Case-insensitive: title containing mongodb
db.articles.find({ title: { $regex: 'mongodb', $options: 'i' } })
Output:
// Returns names starting with A; and titles containing mongodb anywhere (case-insensitive)
📌 Notes
- Only anchored prefixes (^) with case sensitivity can use a normal index
- Escape special characters, e.g. \. matches a literal dot
- Keep $options separate: { $regex: '...', $options: 'i' }
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QHow do I make $regex case-insensitive?
AAdd $options: 'i', e.g. { name: { $regex: 'alice', $options: 'i' } }.
QCan $regex use an index?
AOnly anchored case-sensitive patterns (e.g. ^A) use a normal index; otherwise it is a collection scan.
QShould I use $regex or $text for full-text search?
AFor large text use $text (indexed, stemming); $regex suits small data or exact patterns.