【问题标题】:Spring data mongodb sort on multiple fieldsSpring data mongodb对多个字段进行排序
【发布时间】:2017-06-03 00:41:49
【问题描述】:

我想使用 MongoDB 的 Spring 数据对 MongoDB 中的多个字段进行排序。目前我正在尝试使用聚合来实现这一点:

    Aggregation agg = newAggregation( 
            match(Criteria.where("userId").is(userId)), 
            sort(Sort.Direction.DESC, "type", "createdDate"), 
    );
    AggregationResults<MyBean> results = mongoOperations.aggregate(agg, MyBean.class, MyBean.class);

当我这样做时,它会在 typecreatedDate 上排序 DESC 订单。但我想要DESC 上的typeASC 上的createdDate

我试过了,

    sort(Sort.Direction.DESC, "type");
    sort(Sort.Direction.ASC, "createdDate");

但这只是在createdDate上排序。

【问题讨论】:

    标签: java mongodb mongodb-query aggregation-framework spring-data-mongodb


    【解决方案1】:

    你可以试试这样的。

    Aggregation agg = newAggregation(
            match(Criteria.where("userId").is(userId)),
            sort(Sort.Direction.DESC, "type").and(Sort.Direction.ASC, "createdDate")
    );
    

    【讨论】:

      【解决方案2】:

      有点晚了,但是对于其他人... 试试这个(对于弹簧数据):

      private static final Sort NOTE_SORT = new Sort(new Sort.Order(Sort.Direction.ASC, "seen"),
                                                      new Sort.Order(Sort.Direction.DESC, "date"),
                                                      new Sort.Order(Sort.Direction.ASC, "done"));
      

      【讨论】:

        【解决方案3】:

        您可以创建订单列表并将其用于这样的排序

        List<Order> orders = new ArrayList<>();
        orderQuery.add(new Order(Direction.DESC, "createdDate"));
        Sort sorts = new Sort(orders.toArray(new Order[orders.size()]));    
        Aggregation agg = newAggregation(
                match(Criteria.where("userId").is(userId)),
                sort(sorts)
        );
        

        【讨论】:

          猜你喜欢
          • 2019-03-30
          • 2016-07-01
          • 2016-12-27
          • 1970-01-01
          • 2015-03-24
          • 1970-01-01
          • 2018-07-13
          • 1970-01-01
          • 2011-09-14
          相关资源
          最近更新 更多