2

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 ?

1
  • could you please post your Stock.java ? Commented Sep 19, 2016 at 10:00

1 Answer 1

-1

We can achieve this using Collection sort in java.

Edit class StockDemandPerItem like so:

public class StockDemandPerItem implements Comparable<StockDemandPerItem>{

//existing code goes here
@Override
public int compareTo(StockDemandPerItem compareStockDemand) {
    //descending order
    return compareStockDemand.getDemand().compareTo(this.getDemand());
   } 
} 

Also add this line of code before print loop-

Collections.sort(list);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.