DEV Community

Cover image for Regex in MongoDB
Ifeanyi Chima
Ifeanyi Chima

Posted on

Regex in MongoDB

MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters.

MongoDB provides an operator called $regex. This operator provides regular expression capabilities for pattern matching stings in the queries.

For example, a collection containing 3 documents i.e.,

{
name: "Tony",
position: "Backend developer"
}, 
{
name: "Bruce",
position: "frontend developer"
},  
{
name: "Nick",
position: "HR Manager"
}
Enter fullscreen mode Exit fullscreen mode
db.products.find({position : {$regex : "developer"}}) 
Enter fullscreen mode Exit fullscreen mode

Displaying details of employee who have the word "developer" in their position field:

^ - match at the beginning of a string.

db.products.find({position : {$regex : "^B"}}) 
Enter fullscreen mode Exit fullscreen mode

Displaying details of the employee whose name starts with B:

i - case insensitive

db.products.find({position : {$regex : "Vegetables", $options: "i"}})
Enter fullscreen mode Exit fullscreen mode

Displaying details of employee who are a software engineer with case insensitive

$ - prefix expression

db.products.find({position : {$regex : "e$"}})
Enter fullscreen mode Exit fullscreen mode

Displaying details of the employee whose name ends with e:

Thank you, Please follow me

Buy Me A Coffee

Top comments (0)