Labs ICT
Pro Login

Regular Expressions

Pattern matching in your queries.

Regular Expressions in MongoDB

Regular expressions are like having a superpower for pattern matching. They let you search for text that matches specific patterns, making your queries incredibly flexible.

Think of regex as a sophisticated find-and-replace tool, but for queries. You can search for email patterns, phone numbers, or any text that follows a specific format.

The $regex Operator

The $regex operator lets you use regular expressions in your queries. You can specify patterns to match against field values, and MongoDB will find documents that match the pattern.

You can use regex with the $options modifier to make your patterns more flexible. Common options include "i" for case-insensitive matching and "m" for multi-line matching.

db.users.find({ name: { $regex: "john", $options: "i" } })

db.users.find({ email: { $regex: "@gmail\\.com$" } })

db.products.find({ sku: { $regex: "^PROD-[0-9]{4}" } })
Try it Yourself →

Common Regex Patterns

Here are some practical regex patterns you'll use all the time. These cover common validation scenarios and search patterns that come up in real-world applications.

Remember, regex patterns can be complex, so start simple and build up. It's like learning a new language—start with the basics and add complexity as you get comfortable.

db.users.find({ email: { $regex: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$" } })

db.users.find({ phone: { $regex: "^\\+?[1-9]\\d{1,14}$" } })

db.users.find({ name: { $regex: "^(mr|mrs|ms)\\.", $options: "i" } })
Try it Yourself →

Performance Considerations

While regex is powerful, it can be slow on large collections because MongoDB may need to scan every document. It's like searching for a needle in a haystack—you need to look at everything.

To improve performance, consider adding a text index for simple text searches, or use prefix patterns (patterns that start with a specific string) when possible. Also, try to use anchors like ^ and $ to narrow down your search.

db.users.createIndex({ name: 1 })

db.users.find({ name: { $regex: "^John" } })

db.users.find({ name: { $regex: "son$", $options: "i" } })
Try it Yourself →

🧪 Quick Quiz

What is the $regex operator used for?