![](/img/trans.png)
[英]Custom method to Spring Data Repository with Pageable and Page
[英]Spring Boot, MongoDB, Pageable, sort by a custom method in the object
比如说我有以下设置,
像这样的 model:
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
但它不起作用。
排序文档可以指定对现有字段进行升序或降序排序...
https://docs.mongodb.com/manual/reference/method/cursor.sort/#sort-asc-desc
解决方法:您可以执行MongoDB 聚合,您可以在其中添加具有计算值的新字段并按此值排序:
db.post.aggregate([
{
$addFields: {
upVotes: {
$size: {
$filter: {
input: "$votes.direction",
cond: {
$eq: [ "$$this", 1 ]
}
}
}
}
}
},
{
$sort: {
upVotes: 1
}
}
])
@Autowired
private MongoTemplate mongoTemplate;
...
Aggregation aggregation = Aggregation.newAggregation(addFields, sort);
List<Post> result = mongoTemplate
.aggregate(aggregation, mongoTemplate.getCollectionName(Post.class), Post.class)
.getMappedResults();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.