繁体   English   中英

Spring数据Mongodb Aggregation SORT命令

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM