[英]Spring data Mongodb Aggregation SORT order
我的應用程序使用Spring數據Mongodb,我試圖在嵌入文檔中按降序對數據進行排序,這是行不通的。
請參考以下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
}
]
}
Spring Data 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());
}
電流輸出:
apples :: 150.0
李子:: 200.0
橘子:: 500.0
預期產出(按需求排序):
橘子:: 500.0
李子:: 200.0
apples :: 150.0
你能幫忙按降序獲得預期的輸出嗎?
此外,我計划通過使用上面的限制(1)和Sort-Direction.DESC查詢來找到最大'需求'值。 或者還有其他更好的方法來獲得最大的“需求”價值嗎?
我們可以使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.