2016-09-16 59 views
1

我的应用程序使用Spring数据Mongodb,我试图在嵌入文档内按降序对数据进行排序,但这不起作用。Spring data Mongodb Aggregation SORT order

请参考下面的JSON文件的&聚集查询:

JSON - 股票文件:

{ 
    "_id" : ObjectId("57c6fd7099275c83e6a5b312"), 
    "from" : "China", 
    "stockDemandPerItem" : [ 
     { 
      "item" : "apples", 
      "demand" : 150.0 
     }, 
     { 
      "item" : "plums", 
      "demand" : 200.0 
     }, 
     { 
      "item" : "pears", 
      "demand" : 250.0 
     }, 
     { 
      "item" : "oranges", 
      "demand" : 100.0 
     } 
    ] 
} 

春数据MongoDB的聚合查询:

TypedAggregation<Stock> typedAggr = 
     newAggregation(Stock.class, unwind("stockDemandPerItem"), 
     project("stockDemandPerItem.item", 
     "stockDemandPerItem.demand"), 
      sort(Direction.DESC, "stockDemandPerItem.demand"), 
      limit(3)); 

AggregationResults<StockDemandPerItem> results = mongoTemplate. 
    aggregate(typedAggr, StockDemandPerItem.class); 

List<StockDemandPerItem> list = results.getMappedResults(); 

for(StockDemandPerItem stockDemandPerItem : list) { 
     System.out.println(stockDemandPerItem.getItem() + 
     " :: " + stockDemandPerItem.getDemand()); 
} 

电流输出:

苹果:: 150.0

李子:: 200.0

桔子:: 500.0

期望输出(降序顺序由需求):

桔子:: 500.0

李子:: 200.0

苹果:: 150.0

请问您能否帮助按降序获得预期输出?

此外,我计划通过使用上面的查询限制(1)& Sort-Direction.DESC来查找最大“需求”值。 或者还有其他更好的方法来获得最大的'需求'值吗?

+0

请您发表您的Stock.java之前同时添加这行代码? – alexbt

回答

0

我们可以在java中使用Collection排序来实现这一点。

编辑类StockDemandPerItem像这样:

public class StockDemandPerItem implements Comparable<StockDemandPerItem>{ 

//existing code goes here 
@Override 
public int compareTo(StockDemandPerItem compareStockDemand) { 
    //descending order 
    return compareStockDemand.getDemand().compareTo(this.getDemand()); 
    } 
} 

打印环 -

Collections.sort(list); 
相关问题