java mongo忽略大小写,Java Spring Mongo排序忽略大小写问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值