【问题标题】:Spring Boot, MongoDB, Pageable, sort by a custom method in the objectSpring Boot,MongoDB,Pageable,按对象中的自定义方法排序
【发布时间】:2020-04-22 14:27:46
【问题描述】:

比如说我有以下设置,

这样的模型:

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&amp;size=20&amp;sort=upVotes,但它不起作用。

【问题讨论】:

    标签: java mongodb spring-boot repository pageable


    【解决方案1】:

    排序文档可以指定对现有字段进行升序或降序排序 ...

    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

    弹簧数据

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

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 2015-08-17
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      相关资源
      最近更新 更多