使用Spring Data Mongodb中的Query类进行不区分大小写的排序



我正在使用这种类型的排序,并且我希望不区分大小写。

Query query = new Query();
query.with(new Sort(new Order(Sort.Direction.ASC,"title").ignoreCase()));
return db.find(query, Video.class);

我尝试了这个查询,但没有得到任何结果。

使用的进口:

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

例如,如果我有这种类型的标题:"盗梦空间""黑名单""崇拜"123〃"城市"亡命之徒S";

顺序应为:"123〃"崇拜""黑名单"城市"亡命之徒S"《盗梦空间》;

如果我用这种方式

Query query = new Query();
query.with(new Sort(Sort.Direction.ASC,"title"));
return db.find(query, Video.class);

它返回

"123〃"黑名单""盗梦空间""崇拜"城市"亡命之徒S";

Spring数据mongodb 1.9.2版

使用Collation@Query注释来获得"123","adore","BlackList","city","desperadoS","Inception"的预期排序顺序的另一种方法

文档

@Document(collection = "video")
@Data
public class Video {
@Id
private String id;
private String title;
public Video(String title) {
this.title = title;
}
}

存储库

@Repository
public interface VideoRepository extends MongoRepository<Video, String> {
@Query(collation = "en", value = "{}")
List<Video> getAllSortedVideos(Sort sort);
}

集成测试类来断言的更改

@ActiveProfiles("test")
@SpringBootTest(classes = DemoApplication.class, 
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class VideoRepositoryITest {
@Autowired
private VideoRepository videoRepository;
@Test
void getAllSortedVideos() {
List<String> expectedSystemNamesInOrder = Arrays.asList("123", "adore", "BlackList",
"city", "desperadoS", "Inception");
//breaking the order for fun
Set<String> expectedSystemNamesSet = new HashSet<>(expectedSystemNamesInOrder);
//saving the videos of each title
expectedSystemNamesSet.stream().map(Video::new)
.forEach(videoRepository::save);
//fetching sorted Videos by title
List<Video> videos = videoRepository.getAllSortedVideos(Sort.by(Direction.ASC, "title"));
//fetching sorted Video tiles to assert
List<String> titles = videos.stream().map(Video::getTitle).collect(Collectors.toList());
//asserting the result video title order with the expected order
for (int i = 0; i < titles.size(); i++) {
String actualTitle = titles.get(i);
String expectedTitle = expectedSystemNamesInOrder.get(i);
//Test case will fail if the retrieved title order doesn't match with expected order
Assertions.assertEquals(expectedTitle, actualTitle);
}
}
}

使用org.springframework.data:spring-data-mongodb:3.0.4.RELEASE

使用排序规则对忽略的事例进行排序。示例如下

使用时,您将得到一个IllegalArgumentExceptionnew Order(Sort.Direction.ASC,"title").ignoreCase())

在您的情况下:

Query query = new Query().with(Sort.by(new Sort.Order(Sort.Direction.ASC, "title")));
query.collation(Collation.of("en").strength(Collation.ComparisonLevel.secondary()));
return mongoTemplate.find(query, Video.class);

最新更新