我的应用程序使用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
oranges :: 500.0
预期输出(按需求排序):
oranges :: 500.0
李子:: 200.0
apples :: 150.0
你能帮忙按降序获得预期的输出吗?
另外,我打算找到最大的需求&#39;使用上述查询的限制值(1)&amp;排序Direction.DESC。 或者是否有任何其他更好的方法来获得最大的需求&#39;价值?
答案 0 :(得分:0)
我们可以使用java中的Collection排序来实现这一点。
像这样编辑类StockDemandPerItem:
readOnly
在打印循环之前添加这行代码 -
public class StockDemandPerItem implements Comparable<StockDemandPerItem>{
//existing code goes here
@Override
public int compareTo(StockDemandPerItem compareStockDemand) {
//descending order
return compareStockDemand.getDemand().compareTo(this.getDemand());
}
}