我正在使用Spring-Data-mongodb对MongoDB执行各种请求.
这是我的代码:
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);
注意在Sort.Order对象上应用的.IgnoreCase()方法.
Query .with方法失败,并引发异常:
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)
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);
一切正常,除了我当然不会得到不敏感的排序结果.
因此我可能会得到A B C a1 a2而不是A a1 a2 BC.
即使该异常提到mongoDB不支持IgnoreCase排序,但我使用的是mongo 3.4,据我所知,它确实支持可分页排序(Here’s the official JIRA issue regarding insensitive search feature added)的ignoreCase选项,而spring-data-mongodb软件包为1.8.
解决方法:
强度主要和次要都将提供不区分大小写的排序.确保在排序查询中使用确切的排序规则条件以利用索引.
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);