DEV Community

Cover image for Regex in MongoDB
Ifeanyi Chima
Ifeanyi Chima

Posted on • Edited 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

Match a string

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 a letter

db.name.find({ name: {$regex: /T/} })
Enter fullscreen mode Exit fullscreen mode

The regular expression in this case, /T/ would match any string containing the letter "T".

^ - match at the beginning of a string.

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

Displaying details of the employee whose name starts with B

i - case insensitive

db.employees.find({name: {$regex : "bruce", $options: "i"}})
Enter fullscreen mode Exit fullscreen mode

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

$ - prefix expression

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

Displaying details of the employee whose name ends with e.

Buy Me A Coffee

Thank you, Please follow me

HTML GitHub

Top comments (0)