So i have something that looks like this
db.usuarios.insert
(
[
{
"nome" : "neymala",
"idade" : 40,
"status" : "solteira"
},
{
"nome" : "gabriel",
"idade" : 31,
"status" : "casado"
},
{
"nome" : "jose",
"idade" : 25,
"status" : "solteiro"
},
{
"nome" : "manoel",
"idade" : 25,
"status" : "solteiro",
"interesses" : [
"esporte",
"musica"
]
}
]
)
I would like to find names that starts with ma and ends with l, for example "manoel" or "manuel"
I have figured out how to do one or the other with the fallowing querys:
db.usuarios.find({nome:{$regex: /^ma/ }})
db.usuarios.find({nome:{$regex: /l$/ }})
Now i would like to combine them into a single query.
MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language. Unlike text search, we do not need to do any configuration or command to use regular expressions.
Using this technique we can find a piece of text or a specified word from the string fields. Or in other words, MongoDB allows you to perform a query operation to find the specified text from the string. In MongoDB, we can perform text search using text index and $text operator.
You can combine the two requirements into a single regex:
db.usuarios.find({nome: /^ma.*l$/})
In a regex, .*
means to match 0 or more of any character. So this regex matches names that start with ma
and end with l
, ignoring whatever is between.
combine both querys with a AND opetator
db.usuarios.find({
$and:[
{nome:{$regex: /^ma/ }},
{nome:{$regex: /l$/ }}
]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With