[英]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.