Exact case insensitive match in spring-data mongo

Jesse van Bekkum picture Jesse van Bekkum · May 2, 2014 · Viewed 13.3k times · Source

I am using spring data with mongo, and a repository. Eg:

@Query("{ 'userName' : ?0 }")
public User findByUsername(String username);

I want to make this case insensitive. I have used the following queries:

"{'userName' : { $regex : ?0, $options: 'i' } }"

This works, but it not only matches testUser, but also estUser.

I also tried

"{'userName' : { $regex : ^?0$, $options: 'i' } }"

But this cannot parse the query, because it tries to insert quotes in the regex.

com.mongodb.util.JSONParseException: 
({ $regex : ^"testUser"$, $options: 'i' }
            ^

I get the same kind of problems if I try to use a /.../i regex.

Is there any solution for this, without having to use mongoTemplate, or constructing the regex myself?

Answer

Oliver Drotbohm picture Oliver Drotbohm · May 3, 2014

The easiest way probably is this:

interface UserRepository extends Repository<User, BigInteger> {

   List<User> findByUsernameIgnoreCase(String username);
}