Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring data mongodb how to use wildcards?

I have a field in my mongodb called "name". I am using annotations in spring data to support querying. My question is, is there a way to support wildcard? i.e. If I have values for "name" called "Robert", "Roberto" "Ramano", I could support queries that allow me to pass say "R" to a function, and it will match on everything that starts with R? Right now I have to basically do an "exact spelling" of Robert, or any one of those names to get an exact match.

I know how to do wildcard search with mongodb directly, but am not sure how to do it in java with spring data. I have a model class representing my Student documents that I use annotations to describe how to query.

db.users.find({"name": /.*m.*/})

I don't know how to translate that into java as I want to pass in a variable. For example:

Pseudocode:

String myvar = "R";
db.users.find({/.*<variable here>*/})

The following is what I have on my "MongoRepository" implementation:

public interface UserRepository extends MongoRepository<UserId, String> {
{
    @Query("{'name' : {$regex : ?0}}")
    public List<Users> findByName(String username);
}

When I pass in the full name "Robert", then it is able to find "Robert". However, if I put "R", it does not find anything.

like image 503
Rolando Avatar asked Sep 04 '26 14:09

Rolando


1 Answers

Did you try it with query method?

public interface UserRepository extends MongoRepository<UserId, String> {
{

    public List<Users> findByNameLike(String username);

}
like image 103
loc Avatar answered Sep 07 '26 04:09

loc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!