Regex in MongoDB
Ifeanyi Chima
Posted on August 24, 2023
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"
}
Match a string
db.products.find({position : {$regex : "developer"}})
Displaying details of employee who have the word "developer" in their position field.
Match a letter
db.name.find({ name: {$regex: /T/} })
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"}})
Displaying details of the employee whose name starts with B
i - case insensitive
db.employees.find({name: {$regex : "bruce", $options: "i"}})
Displaying details of employee who are a software engineer with case insensitive
$ - prefix expression
db.employees.find({name: {$regex : "e$"}})
Displaying details of the employee whose name ends with e.
Thank you, Please follow me
Posted on August 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.