I want to make a text search case insensitive with regex query with spring-data mongo
.
For example in Oracle :
select * from user where lower(username) like '%ab%'
How can i make this query with spring-data mongo
?
Thanks in advance
You can try something like below. Assumes you have a User
pojo class.
Using MongoTemplate
i
option for case insensitive:
Criteria regex = Criteria.where("username").regex(".*ab.*", "i");
mongoOperations.find(new Query().addCriteria(regex), User.class);
Using MongoRepository (Case sensitive)
List<User> users = userRepository.findByUserNameRegex(".*ab.*");
interface UserRepository extends MongoRepository<User, String> {
List<User> findByUserNameRegex(String userName);
}
Using MongoRepository with Query dsl (Case sensitive)
List<User> users = userRepository.findByQuery(".*ab.*");
interface UserRepository extends MongoRepository<User, String> {
@Query("{'username': {$regex: ?0 }})")
List<User> findByQuery(String userName);
}
For Non-Regex based query you can now utilize case insensitive search/sort through collation with locale and strength set to primary or secondary:
Query query = new Query(filter);
query.collation(Collation.of("en").
strength(Collation.ComparisonLevel.secondary()));
mongoTemplate.find(query,clazz,collection);