Sergey Shcherbakov
Sergey Shcherbakov

Reputation: 4778

Spring Data Mongodb findBy In case insensitive

I'm trying to create a Spring Data MongoDB repository method that could perform case insensitive search for fields from a given list, that is functionality similar to SQL 'IN' operator.

In my repository I have following methods:

User findByUsername(@Param("username") String username);
User findByUsernameIgnoreCase(@Param("username") String username);
Page<User> findByUsernameIn(@Param("username") List<String> username, Pageable pageable);
Page<User> findByUsernameIgnoreCaseIn(@Param("username") List<String> username, Pageable pageable);
Page<User> findByUsernameInIgnoreCase(@Param("username") List<String> username, Pageable pageable);
Page<User> findByUsernameInAllIgnoreCase(@Param("username") List<String> username, Pageable pageable);

I'm also exposing repository as REST resource using @RepositoryRestResource

The first three methods work very well as I expect. The case gets ignored by search when using findByUsernameIgnoreCase. The users are correclty found using the given string list in findByUsernameIn.

My problem is that I cannot combine In and IgnoreCase suffixes. The last two methods also work, but they don't ignore case of the string as I want them to do.

Is there a way to perform case insensitive IN search not falling back to explicitly specifying the MongoDB @Query?

(Tried that with spring-data-mongodb:1.8.4, spring-data-rest-core:2.4.4)

Upvotes: 10

Views: 3894

Answers (1)

Noel
Noel

Reputation: 10525

One way to force case insensitive search is by changing the collation settings. By default strength is 3. You need to set it to 2, to make it case insensitive.

@Query(collation = "{'locale': 'en_US', 'strength': 2}")
Page<User> findByUsernameIn(@Param("username") List<String> username, Pageable pageable);

Upvotes: 2

Related Questions