Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)

I am planning to make a text search case insensitive with a regex query with spring-data mongo.

For instance in Oracle :

select * from user where lower(username) like '%ab%'

Can you please help me to make this query with spring-data mongo?

1 Answer

0 votes
by (11.7k points)

I think you should try the thing listed down below in your MongoDB(I am assuming you have a User pojo class):

By 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);

}

Now, case insensitive search/sort can be utilized  through collation for non-regex query 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);

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...