Spring Data mongodb聚合|基于枚举属性顺序的自定义排序

1sbrub3j  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(162)

I'm trying to sort a data set based on the order (ordinal) of the enum attributes. Let's say I have the following enum

public enum Status {
  IN_PROGRESS,
  RESOLVED,
  NEW
}

Based on the above I want my dataset to be sorted as NEW, IN_PROGRESS & RESOLVED order rather than the alphabetical order of the enum name.
I'm already using aggregation to perform some filtering. So now I need a way to achieve custom sorting with my aggregation

Aggregation.newAggregation(Case.class,
            match(filterCriteria),
            sort(generateCustomSort()),
            limit(limit),
            skip(skipCount)):

I know for a fact that with JPA we have the @Enumerated annotation & we can set it to use the ordinal of the enum to sort the data. Is there something similar in Spring data MongoDB? Or with a projections can we do this?

b4lqfgs4

b4lqfgs41#

不可能,因为MongoDB不允许排序定制(B树的东西)。

**解决方法:**添加枚举编号,将编号存储在Mongodb文档中并使用它们进行订购

public enum Status {
  IN_PROGRESS(2),
  RESOLVED(3),
  NEW(1);

  private int id;

  Status(int id){
      this.id = id;
  }
}

相关问题