MongoDB Query to Find Documents Using Regex
db.collection.find({ field: { $regex: /pattern/ } }) to find documents where the field matches the regex pattern in MongoDB.Examples
How to Think About It
$regex operator in the query to match text fields against that pattern. MongoDB will return all documents where the field text fits the regex.Algorithm
Code
db.users.insertMany([
{ name: "Alice", email: "alice@gmail.com" },
{ name: "Bob", email: "bob@yahoo.com" },
{ name: "Adam", email: "adam@gmail.com" }
]);
const cursor = db.users.find({ name: { $regex: /^A/ } });
cursor.forEach(doc => printjson(doc));Dry Run
Let's trace the query { name: { $regex: /^A/ } } on the users collection.
Check first document
Document: { name: "Alice" } matches regex /^A/ because name starts with 'A'.
Check second document
Document: { name: "Bob" } does not match regex /^A/ because name starts with 'B'.
Check third document
Document: { name: "Adam" } matches regex /^A/ because name starts with 'A'.
| Document Name | Matches /^A/ |
|---|---|
| Alice | Yes |
| Bob | No |
| Adam | Yes |
Why This Works
Step 1: Using $regex operator
The $regex operator tells MongoDB to match the field value against the given regular expression.
Step 2: Pattern matching
The regex /^A/ matches any string starting with the letter 'A', so only those documents are returned.
Step 3: Case sensitivity
By default, regex is case sensitive. You can add i flag for case-insensitive matching.
Alternative Approaches
db.users.find({ name: { $regex: "^A" } })db.users.find({ name: { $regex: "^a", $options: "i" } })Complexity: O(n) time, O(1) space
Time Complexity
The query scans each document's field to check regex match, so time grows linearly with number of documents.
Space Complexity
No extra space is needed beyond the output; matching is done in place.
Which Approach is Fastest?
Using indexed fields with regex anchored at start (e.g., /^pattern/) can be faster; unanchored regex scans all documents.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $regex with anchored pattern | O(n) | O(1) | Fast prefix matching |
| $regex with options | O(n) | O(1) | Case-insensitive matching |
| String pattern in $regex | O(n) | O(1) | Simple regex without flags |
i option with $regex for case-insensitive searches.