2016-09-16 3 views
1

내 응용 프로그램은 Spring 데이터 Mongodb를 사용하며 포함되지 않은 문서 내에서 내림차순으로 데이터를 정렬하려고합니다.Spring 데이터 Mongodb 집계 정렬 순서

{ 
    "_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()); 
} 

전류 출력 - 주식 문서

JSON :

JSON 문서 아래 & 집계 쿼리를 참조하시기 바랍니다 :

사과 :: 150.0

자두 : 200.0

오렌지 : (수요 내림차순 순서) 500.0

예상 출력 :

오렌지 : 500.0

자두 :: 200.0

사과 : 150.0

내림차순으로 예상 출력을 얻으시겠습니까?

또한 limit (1) & Sort-Direction.DESC를 사용하여 위의 쿼리를 사용하여 최대 '수요'값을 찾을 계획입니다. 아니면 '수요'가치를 극대화 할 수있는 더 좋은 방법이 있습니까?

+0

당신이 당신의 Stock.java을 게시하시기 바랍니다 수있는 루프 인 인쇄하기 전에 코드 줄을 추가? – alexbt

답변

0

Java에서 Collection sort를 사용하여이 작업을 수행 할 수 있습니다.

편집 클래스 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);