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"
}
db.products.find({position : {$regex : "developer"}})
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"}})
Displaying details of the employee whose name starts with B:
i - case insensitive
db.products.find({position : {$regex : "Vegetables", $options: "i"}})
Displaying details of employee who are a software engineer with case insensitive
$ - prefix expression
db.products.find({position : {$regex : "e$"}})
Displaying details of the employee whose name ends with e:
Thank you, Please follow me
Top comments (0)