Pranab Choudhury
Pranab Choudhury

Reputation: 31

Firestore - Orderby Descending

In my Firestore database I have field index no, datatype is string but he data is number like 1, 2, 3 and so on.

collectionReference
     .orderBy("indexNo", Query.Direction.DESCENDING)

the output is ok till 9, after 9 i.e., for 10, 11, 12, the data is displayed 1, 10, 11, 12, 2, 3 and so on.

Pleas guide me to resolve it, as these numbers will decide the arrangement of cardview items in recycler view.

Thanks...

Upvotes: 2

Views: 2996

Answers (3)

Alex Mamo
Alex Mamo

Reputation: 138824

If the data type of your indexNo property is of type String and if you want to order the results using Query.Direction.DESCENDING, the result will be not the expected one because when you order strings, the results are ordered lexicographically. There are two ways in which you can solve this issue. The first one would be to change the data type of your property from String to number, which I personally recommend it.

This is the normal order for numbers:

  • 1308
  • 1309
  • 1310
  • 1311

And this is the normal order for strings:

  • "1308"
  • "1309"
  • "131"
  • "1310"

The second approach would be to modify the data to get the behavior you want. For numbers, you can accomplish that by padding them with zeroes, like in the example below:

  • "0131" //zero added before
  • "0132" //zero added before
  • ......
  • "1308"
  • "1309"
  • "1310"
  • "1311"

Upvotes: 4

Pranab Choudhury
Pranab Choudhury

Reputation: 31

Better to change data type from string to integer. I did it. Thanks for your support.

Upvotes: 0

Dorkmania
Dorkmania

Reputation: 962

The ordering is lexicographic since the data-type is string. Think of the numbers as alphabets. 0 = A, 1 = B, 2 = C... When comparing 9 and 10, think of it like comparing the words 'I' and 'BA'. In a dictionary, which would you expect to appear first?

Upvotes: 0

Related Questions