---
description: Regular expressions are used for pattern matching, which is basically for findings strings within documents. Sometimes when retrieving documents in a collection, you may not know exactly what the exac
title: MongoDB Regular Expression ($regex) with Examples
image: https://www.guru99.com/images/mongodb-regular-expression-regex.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

MongoDB regular expressions perform pattern matching to find strings inside documents, using the $regex operator, the $options flag for case insensitivity, anchors for exact matches, and slash delimiters when the exact field value is unknown.

* 🔍 **$regex Operator:** db.collection.find({field:{$regex:”pattern”}}) matches documents containing the pattern.
* 🎯 **Anchors:** ^ and $ force exact matches, binding the pattern to the string start and end.
* 🔠 **Case Insensitivity:** The $options ‘i’ flag matches text regardless of upper or lower case.
* ➗ **Slash Delimiters:** Wrapping a pattern in /…/ matches without writing the $regex operator.
* 📉 **Last N Documents:** Combine sort({\_id:-1}) with limit(n) to return the newest records.
* 🤖 **AI Assist:** Assistants build regex patterns and flag full-collection-scan performance costs.

[ Read More ](javascript:void%280%29;) 

![MongoDB Regular Expression \(Regex\)](https://www.guru99.com/images/mongodb-regular-expression-regex.png)

Regular expressions are used for pattern matching, which is basically for finding strings within documents.

Sometimes when retrieving documents in a collection, you may not know exactly what the exact Field value to search for. Hence, one can use regular expressions to assist in retrieving data based on pattern matching search values.

## Using $regex operator for Pattern matching

The $regex operator in MongoDB is used to search for specific strings in the collection. The following example shows how this can be done.

Let us assume that we have our same Employee collection which has the Field names of “Employeeid” and “EmployeeName”. Let us also assume that we have the following documents in our collection.

| Employee id | Employee Name |
| ----------- | ------------- |
| 22          | NewMartin     |
| 2           | Mohan         |
| 3           | Joe           |
| 4           | MohanR        |
| 100         | Guru99        |
| 6           | Gurang        |

Here in the below code we have used the $regex operator to specify the search criteria.

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr1.png)

db.Employee.find({EmployeeName : {$regex: "Gu" }}).forEach(printjson)

**Code Explanation:**

1. Here we want to find all Employee Names which have the characters ‘Gu’ in it. Hence, we specify the $regex operator to define the search criteria of ‘Gu’.
2. The printjson is being used to print each document which is returned by the query in a better way.

If the command is executed successfully, the following Output will be shown:

**Output:**

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr2.png)

The output clearly shows that those documents wherein the Employee Name contains the ‘Gu’ characters are returned.

If suppose your collection has the following documents with an additional document which contained the Employee Name as “Guru999”. If you entered the search criteria as “Guru99”, it would also return the document which had “Guru999”. But suppose if we did not want this and only wanted to return the document with “Guru99”. Then we can do this with exact pattern matching. To do an exact pattern matching, we will use the ^ and $ character. We will add the ^ character in the beginning of the string and $ at the end of the string.

| Employee id | Employee Name |
| ----------- | ------------- |
| 22          | NewMartin     |
| 2           | Mohan         |
| 3           | Joe           |
| 4           | MohanR        |
| 100         | Guru99        |
| 6           | Gurang        |
| 8           | Guru999       |

The following example shows how this can be done.

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr3.png)

db.Employee.find({EmployeeName : {$regex: "^Guru99$"}}).forEach(printjson)

**Code Explanation:**

1. Here in the search criteria, we are using the ^ and $ character. The ^ is used to make sure that the string starts with a certain character, and $ is used to ensure that the string ends with a certain character. So when the code executes it will fetch only the string with the name “Guru99”.
2. The printjson is being used to print each document which is returned by the query in a better way.

If the command is executed successfully, the following Output will be shown:

**Output:**

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr4.png)

In the output, it is clearly visible that string “Guru99” is fetched.

## Pattern Matching with $options

When using the $regex operator one can also provide additional options by using the **$options** keyword. For example, suppose you wanted to find all the documents which had ‘Gu’ in their Employee Name, irrespective of whether it was case sensitive or insensitive. If such a result is desired, then we need to use the **$options** with the case insensitivity parameter.

The following example shows how this can be done.

Let us assume that we have our same Employee collection which has the Field names of “Employeeid” and “EmployeeName”.

Let us also assume that we have the following documents in our collection.

| Employee id | Employee Name |
| ----------- | ------------- |
| 22          | NewMartin     |
| 2           | Mohan         |
| 3           | Joe           |
| 4           | MohanR        |
| 100         | Guru99        |
| 6           | Gurang        |
| 7           | GURU99        |

Now if we run the same query as in the last topic, we would never see the document with “GURU99” in the result. To ensure this comes in the result set, we need to add the $options “i” parameter.

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr5.png)

db.Employee.find({EmployeeName:{$regex: "Gu",$options:'i'}}).forEach(printjson)

**Code Explanation:**

1. The $options with the ‘i’ parameter (which means case insensitivity) specifies that we want to carry out the search no matter if we find the letters ‘Gu’ in lower or upper case.

If the command is executed successfully, the following Output will be shown:

**Output:**

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr6.png)

1. The output clearly shows that even though one document has the upper case ‘Gu’, the document still gets displayed in the result set.

### RELATED ARTICLES

* [MongoDB Array of Objects using insert() with Example ](https://www.guru99.com/add-mongodb-array-using-insert.html "MongoDB Array of Objects using insert() with Example")
* [20 MongoDB Interview Questions and Answers (2026) ](https://www.guru99.com/mongodb-interview-questions.html "20 MongoDB Interview Questions and Answers (2026)")
* [9 MongoDB Alternatives (Open Source) in 2026 ](https://www.guru99.com/mongodb-alternative.html "9 MongoDB Alternatives (Open Source) in 2026")
* [MongoDB vs MySQL – Difference Between Them ](https://www.guru99.com/mongodb-vs-mysql.html "MongoDB vs MySQL – Difference Between Them")

## Pattern matching without the regex operator

One can also do pattern matching without the $regex operator. The following example shows how this can be done.

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr7.png)

db.Employee.find({EmployeeName: /Gu/}).forEach(printjson)

**Code Explanation:**

1. The “//” delimiters basically mean to specify your search criteria within these delimiters. Hence, we are specifying /Gu/ to again find those documents which have ‘Gu’ in their EmployeeName.

If the command is executed successfully, the following Output will be shown:

**Output:**

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr8.png)

The output clearly shows that those documents wherein the Employee Name contains the ‘Gu’ characters are returned.

## Fetching last ‘n’ documents from a collection

There are various ways to get the last n documents in a collection.

Let us look at one of the ways via the following steps.

The following example shows how this can be done.

Let us assume that we have our same Employee collection which has the Field names of “Employeeid” and “EmployeeName”.

Let us also assume that we have the following documents in our collection:

| Employee id | Employee Name |
| ----------- | ------------- |
| 22          | NewMartin     |
| 2           | Mohan         |
| 3           | Joe           |
| 4           | MohanR        |
| 100         | Guru99        |
| 6           | Gurang        |
| 7           | GURU99        |

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr9.png)

db.Employee.find().sort({_id:-1}).limit(2).forEach(printjson)

**Code Explanation:**

1. When querying for the documents, use the sort function to sort the records in reverse order based on the \_id field value in the collection. The -1 basically indicates to sort the documents in reverse order or descending order so that the last document becomes the first document to be displayed.
2. Then use the limit clause to just display the number of records you want. Here we have set the limit clause (2), so it will fetch the last two documents.

If the command is executed successfully, the following Output will be shown:

**Output:**

[](https://www.guru99.com/images/MongoDB/112115%5F0512%5FRegularexpr10.png)

The output clearly shows that the last two documents in the collection are displayed. Hence we have clearly shown that to fetch the last ‘n’ documents in the collection, we can first sort the documents in descending order and then use the limit clause to return the ‘n’ number of documents which are required.

**Note**: If the search is performed on a string which is greater than say 38,000 characters, it will not display the right results.

## FAQs

🎯 How do I match an exact string with MongoDB $regex?

Anchor the pattern with ^ and $. The pattern “^Guru99$” matches only “Guru99” and rejects “Guru999”, because ^ binds the start of the string and $ binds the end.

⚡ Does MongoDB $regex use indexes?

Only case-sensitive patterns with a ^ prefix use an index efficiently. Unanchored or case-insensitive patterns trigger a full collection scan, so anchor the prefix whenever possible.

🔤 How do I escape special characters in a $regex pattern?

Precede metacharacters such as dot, star, plus, or brackets with a backslash. For example, the pattern for a literal “.com” ending escapes the dot so it is not treated as any character.

🆚 What is the difference between $regex and $text search?

$regex does flexible pattern matching on one field and can scan the whole collection. $text uses a text index for fast word-based search across indexed fields but does not support partial-substring patterns.

📏 Is there a length limit for MongoDB $regex searches?

Yes. When the searched string exceeds roughly 38,000 characters, the query may not return correct results. Keep patterns and target fields within that limit for reliable matching.

🚀 How can I speed up slow $regex queries?

Store a lowercased copy of the field for case-insensitive lookups, anchor patterns with ^, and prefer a text index or Atlas Search on large collections instead of unanchored $regex.

🤖 How does AI help write MongoDB regex queries?

AI assistants turn plain-English rules into $regex patterns, add the correct anchors and $options flag, and warn when a query will trigger a slow full collection scan.

🧠 Can an AI Copilot optimize a MongoDB $regex query?

Yes. An AI Copilot rewrites unanchored patterns, recommends a text index or Atlas Search, and converts case-insensitive $regex into a lowercased-field lookup for speed.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/mongodb-regular-expression-regex.png","url":"https://www.guru99.com/images/mongodb-regular-expression-regex.png","width":"700","height":"250","caption":"MongoDB Regular Expression ($regex)","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/regular-expressions-mongodb.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/mongodb","name":"MongoDB"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/regular-expressions-mongodb.html","name":"MongoDB Regular Expression ($regex) with Examples"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/regular-expressions-mongodb.html#webpage","url":"https://www.guru99.com/regular-expressions-mongodb.html","name":"MongoDB Regular Expression ($regex) with Examples","dateModified":"2026-07-02T11:59:49+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/mongodb-regular-expression-regex.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/regular-expressions-mongodb.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/stephen","name":"Stephen Twain","description":"I am Stephen Twain, a MongoDB Developer, providing expert guidance to help you master database management with clear, practical MongoDB tutorials.","url":"https://www.guru99.com/author/stephen","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/stephen-twain-author.png","url":"https://www.guru99.com/images/stephen-twain-author.png","caption":"Stephen Twain","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"@type":"NewsArticle","headline":"MongoDB Regular Expression ($regex) with Examples","keywords":"mongodb","dateModified":"2026-07-02T11:59:49+05:30","articleSection":"MongoDB","author":{"@id":"https://www.guru99.com/author/stephen","name":"Stephen Twain"},"publisher":{"@id":"https://www.guru99.com/#organization"},"description":"Regular expressions are used for pattern matching, which is basically for findings strings within documents. Sometimes when retrieving documents in a collection, you may not know exactly what the exac","copyrightYear":"2026","copyrightHolder":{"@id":"https://www.guru99.com/#organization"},"name":"MongoDB Regular Expression ($regex) with Examples","@id":"https://www.guru99.com/regular-expressions-mongodb.html#richSnippet","isPartOf":{"@id":"https://www.guru99.com/regular-expressions-mongodb.html#webpage"},"image":{"@id":"https://www.guru99.com/images/mongodb-regular-expression-regex.png"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/regular-expressions-mongodb.html#webpage"}}]}
```
