Is it possible to sort only results that matches a condition in Spring Mongo? Let us say I have this data:
Color | Fruit | Amount |
---|---|---|
Orange | Orange | 23 |
Red | Apple | 4 |
Red | Strawberry | 66 |
Yellow | Banana | 2 |
I want to sort the list to display the Fruits with color red on Top and the remaining fruits will be sorted by amount. So the resulting table should be.
Color | Fruit | Amount |
---|---|---|
Red | Apple | 4 |
Red | Strawberry | 66 |
Yellow | Banana | 2 |
Orange | Orange | 23 |
So far here is what I've tried using aggregation.
val match1: MatchOperation = Aggregation.match(Criteria("Color").`is`("Red"))
val match2: MatchOperation = Aggregation.match(Criteria("Color").`is`("Red").not())
val sortByAmount= sort(Sort.Direction.ASC, "Amount")
val aggregation = Aggregation.newAggregation(match1, sortByAmount, match2, sortByAmount)
val output: AggregationResults<Fruits> = mongoTemplate.aggregate(aggregation, "fruits", Fruits::class.java)
But I'm only getting this as a result
Color | Fruit | Amount |
---|---|---|
Red | Apple | 4 |
Red | Strawberry | 66 |