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?
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.
As mentioned by @natac13 and @007_jb mongo shell is an interactive javascript interpreter and hence it is also case-sensitive.
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.
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.
I just tried the following and it worked for me.
@Query(value = "{'name': {$regex : '^?0$', $options: 'i'}}")
List<Item> findItemsByNameRegexExactMatch(String name);
^ for the start, $ for the end
Aggregation aggregation = newAggregation( match(Criteria.where("fieldName").regex("^"+searchText+"$","i")) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With