$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.

CategoryElement & Evaluation
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ <field>: { $regex: <pattern>, $options: '<options>' } }

⚙️ Parameters

fieldThe document field to match.
regexA PCRE-style regular expression pattern.
optionsOptional: 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏