gpt4 book ai didi

java - Spring Boot、MongoDB、Pageable、按对象中的自定义方法排序

转载 作者:行者123 更新时间:2023-12-01 17:16:54 25 4
gpt4 key购买 nike

例如,我有以下设置,

这样的模型:

public class Post {

@Id
private String id;
private String post;
private List<Vote> votes = new ArrayList<>();

// Getters & Setters...
public double getUpVotes() {
return votes.stream().filter(vote -> vote.getDirection() == 1).mapToInt(Vote::getDirection).count();
}
}

public class Vote {

private short direction;

// Getters & Setters...
}

然后是像这样的存储库

@Repository
public interface PostRepository extends PagingAndSortingRepository<Post, String> {

List<Post> findAll(Pageable pageable);
}

并假设我想根据 getter 方法的结果对帖子进行排序 getUpVotes()

我已尝试以下 localhost:3005/opinion?page=0&size=20&sort=upVotes 但它不起作用。

最佳答案

The sort document can specify ascending or descending sort on existing fields ...

https://docs.mongodb.com/manual/reference/method/cursor.sort/#sort-asc-desc

解决方法:您可以执行 MongoDB aggregation您可以在其中添加具有计算值的新字段并按该值排序:

db.post.aggregate([
{
$addFields: {
upVotes: {
$size: {
$filter: {
input: "$votes.direction",
cond: {
$eq: [ "$$this", 1 ]
}
}
}
}
}
},
{
$sort: {
upVotes: 1
}
}
])

MongoPlayground | $project

Spring 数据

@Autowired
private MongoTemplate mongoTemplate;
...

Aggregation aggregation = Aggregation.newAggregation(addFields, sort);
List<Post> result = mongoTemplate
.aggregate(aggregation, mongoTemplate.getCollectionName(Post.class), Post.class)
.getMappedResults();

关于java - Spring Boot、MongoDB、Pageable、按对象中的自定义方法排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61367637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com