Sorting documents by multiple attributes is not working correctly
GurtejSohi opened this issue · 1 comments
Problem
When we provide multiple OrderBy
s in a query, it sometimes returns the documents in an incorrect order. For example, if we try to sort the documents based on field1
and then field2
, it works incorrectly in some cases:
query.addAllOrderBys(List.of(new OrderBy("field1", true), new OrderBy("field2", false)));
This is tested using MongoCollection.
Cause
The orderBy list is converted to a HashMap which may not preserve the order of the keys(as in the list) -
https://github.com/hypertrace/document-store/blob/main/document-store/src/main/java/org/hypertrace/core/documentstore/mongo/MongoCollection.java#L365
So, in the above example, it can happen that the sorting happens first on field2
and then on field1
.
One possible solution is that we can use LinkedHashMap
instead of HashMap
for the orderbyMap
.