Search code examples
javaspringmongodbspring-data

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.


Solution

  • Did you try it with query method?

    public interface UserRepository extends MongoRepository<UserId, String> {
    {
    
        public List<Users> findByNameLike(String username);
    
    }