Spring Boot、MongoDB、Pageable,通过对象中的自定义方法进行排序



例如,我有以下设置,

像这样的模型:

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
}
}
])

MongoPlayground|$project

弹簧数据

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

最新更新