Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact case insensitive match in spring-data mongo

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?

like image 301
Jesse van Bekkum Avatar asked May 02 '14 08:05

Jesse van Bekkum


People also ask

How do I do a case insensitive search in MongoDB?

To use a case insensitive index on a collection with no default collation, create an index with a collation and set the strength parameter to 1 or 2 (see Collation for a detailed description of the strength parameter). You must specify the same collation at the query level in order to use the index-level collation.

Is MongoDB data case sensitive?

As mentioned by @natac13 and @007_jb mongo shell is an interactive javascript interpreter and hence it is also case-sensitive.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

Does Spring support MongoDB?

The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a Repository style data access layer.


2 Answers

I just tried the following and it worked for me.

 @Query(value = "{'name': {$regex : '^?0$', $options: 'i'}}")
    List<Item> findItemsByNameRegexExactMatch(String name);
like image 146
Sergey Benner Avatar answered Sep 23 '22 04:09

Sergey Benner


^ for the start, $ for the end

Aggregation aggregation = newAggregation( match(Criteria.where("fieldName").regex("^"+searchText+"$","i")) );
like image 33
Sudhakar Reddy Avatar answered Sep 22 '22 04:09

Sudhakar Reddy