2016-09-16 101 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); 
相關問題