My application uses Spring data Mongodb and I am trying to sort the data in descending order inside the embedded document, which is NOT working.
Please refer the below JSON document & Aggregation query:
JSON - Stock document:
{
"_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 Aggregation query:
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());
}
Current Output:
apples :: 150.0
plums :: 200.0
oranges :: 500.0
Expected Output (desc order by demand):
oranges :: 500.0
plums :: 200.0
apples :: 150.0
Could you please help to get the expected output in descending order ?
Also, I am planning to find the maximum 'demand' value by using the above query with limit(1) & Sort-Direction.DESC. Or else is there any other better approach to get the maximum 'demand' value ?