I am using Spring-Data-mongodb performing all kind of requests to MongoDB.
When trying to perform paging & sort with ignore case I get an exception,
Here's my code:
Sort.Order order = new Sort.Order(ascending? Sort.Direction.ASC: Sort.Direction.DESC, sortKey).ignoreCase();
Query query = new Query(filter).with(new PageRequest(page, size, new Sort(order)));
return mongoTemplate.find(query, clazz,collection);
notice the .IgnoreCase() method applied on the Sort.Order Object.
The Query .with Method fails and throws the exception:
java.lang.IllegalArgumentException: Given sort contained an Order for lastName with ignore case! MongoDB does not support sorting ignoreing case currently!
at org.springframework.data.mongodb.core.query.Query.with(Query.java:179)
at org.springframework.data.mongodb.core.query.Query.with(Query.java:162)
If removing the .IgnoreCase() method, i.e executing the following code:
Sort.Order order = new Sort.Order(ascending? Sort.Direction.ASC: Sort.Direction.DESC, sortKey);
Query query = new Query(filter).with(new PageRequest(page, size, new Sort(order)));
return mongoTemplate.find(query, clazz,collection);
Everything works fine, except of course I don't get insensitive sorted results.
hence I might get A B C a1 a2, instead of A a1 a2 B C.
Even though the exception mentions that mongoDB doesn't support IgnoreCase sort, I am using mongo 3.4 which in my understanding does support ignoreCase option for pageable sort (Here's the official JIRA issue regarding insensitive search feature added), and my spring-data-mongodb package is 1.8.
解决方案
Sorry if my comments were not clear. You've to send collation with sort query.
Strength primary and secondary both will provide case insensitive sort. Make sure you use the exact collation criteria in your sort query to take advantage of index.
Sort.Order order = new Sort.Order(ascending? Sort.Direction.ASC: Sort.Direction.DESC, sortKey);
Query query = new Query(filter).with(new PageRequest(page, size, new Sort(order)));
query.collation(Collation.of("en").strength(Collation.ComparisonLevel.secondary()));
return mongoTemplate.find(query, clazz,collection);