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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay