← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 5 of 7

Regex

$regex matches strings against regular expressions for pattern searches.

In this page:

  1. Regex
Syntax
javascript
{ 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

bash
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
  1. Using unanchored regex on large collections
  2. Forgetting the i option
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.