0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Find Documents Using Regex

Use db.collection.find({ field: { $regex: /pattern/ } }) to find documents where the field matches the regex pattern in MongoDB.
📋

Examples

Input{ name: { $regex: /^A/ } }
Output[{ "name": "Alice" }, { "name": "Adam" }]
Input{ email: { $regex: /@gmail\.com$/ } }
Output[{ "email": "user1@gmail.com" }, { "email": "test@gmail.com" }]
Input{ city: { $regex: /new/i } }
Output[{ "city": "New York" }, { "city": "newark" }]
🧠

How to Think About It

To find documents matching a pattern, think of the regex as a flexible search term. Use $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

1
Identify the field to search in the documents.
2
Write the regex pattern to match the desired text.
3
Use the <code>$regex</code> operator with the pattern in the find query.
4
Run the query to get all matching documents.
💻

Code

mongodb
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));
Output
{ "_id" : ObjectId("...") , "name" : "Alice", "email" : "alice@gmail.com" } { "_id" : ObjectId("...") , "name" : "Adam", "email" : "adam@gmail.com" }
🔍

Dry Run

Let's trace the query { name: { $regex: /^A/ } } on the users collection.

1

Check first document

Document: { name: "Alice" } matches regex /^A/ because name starts with 'A'.

2

Check second document

Document: { name: "Bob" } does not match regex /^A/ because name starts with 'B'.

3

Check third document

Document: { name: "Adam" } matches regex /^A/ because name starts with 'A'.

Document NameMatches /^A/
AliceYes
BobNo
AdamYes
💡

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

Using $regex with string pattern
mongodb
db.users.find({ name: { $regex: "^A" } })
This uses a string pattern instead of regex literal; works the same but less flexible for complex regex.
Using $regex with options
mongodb
db.users.find({ name: { $regex: "^a", $options: "i" } })
Adds case-insensitive option to match names starting with 'a' or 'A'.

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.

ApproachTimeSpaceBest For
$regex with anchored patternO(n)O(1)Fast prefix matching
$regex with optionsO(n)O(1)Case-insensitive matching
String pattern in $regexO(n)O(1)Simple regex without flags
💡
Use the i option with $regex for case-insensitive searches.
⚠️
Forgetting to escape special characters in regex patterns, causing unexpected matches or errors.