Regex
$regex matches strings against regular expressions for pattern searches.
In this page:
Syntax
{ field: /pattern/ }
{ field: { $regex: "pattern", $options: "i" } }
Regex
Use { field: /pattern/ } or { $regex: "pattern", $options: "i" } for case-insensitive matching. Anchored, case-sensitive prefix patterns such as /^abc/ can use an index efficiently; unanchored ones scan.
For real text search use a text index or Atlas Search instead.
Note:
Anchor patterns with ^ to take advantage of indexes.
Example: Regex
test> db.people.insertMany([{ _id: 1, name: "Ada" }, { _id: 2, name: "adam" }, { _id: 3, name: "Bob" }, { _id: 4, name: "Nadia" }])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.people.find({ name: /^ad/i }, { _id: 0 })
[ { name: 'Ada' }, { name: 'adam' } ]
test> db.people.find({ name: { $regex: "a$" } }, { _id: 0 })
[ { name: 'Ada' }, { name: 'Nadia' } ]
test> db.people.find({ name: /^Ad/ }, { _id: 0 })
[ { name: 'Ada' } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using unanchored regex on large collections
- Forgetting the i option
- Passing user input into a regex unescaped
Chapter Summary
- /pattern/ or $regex with options
- i makes it case-insensitive
- Anchored prefixes use indexes
- Escape user input
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: