Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB regex string startswith and endswith [duplicate]

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.

like image 341
user56130 Avatar asked Nov 25 '18 16:11

user56130


People also ask

How regex works in MongoDB?

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.

How do I search for a part of a string in MongoDB?

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.


2 Answers

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.

like image 65
JohnnyHK Avatar answered Oct 18 '22 00:10

JohnnyHK


combine both querys with a AND opetator

db.usuarios.find({
$and:[
    {nome:{$regex: /^ma/ }},
    {nome:{$regex: /l$/ }}
]

})
like image 10
user56130 Avatar answered Oct 18 '22 00:10

user56130