Spring数据mongodb:根据两个字段的差异查询排序结果

Spring data mongodb: query and sort results based on difference of two fields

假设我有一个如下定义的集合:

@Document(collection = "Item")
public class Item {
    @Id
    private String id;
    private String title;
    private String mrp;
    private String discount;

    //getters and setters goes here
}

我需要找到所有按 [mrp - 折扣] 值排序的 项目

如何用MongoOperations

表达

这就是 Aggregation Framework 的用途。 Spring 数据 MongoDB 通过 MongoOperations 提供 aggregate

TypedAggregation<Item> agg = newAggregation(Item.class, 
  project()
    .andExpression("mrp - discount").as("total")
    .andInclude("mrp", "discount", "id"),
  sort(new Sort(ASC, "total")));