1

The following is stated in the official documentation:

By default, a query retrieves all documents that satisfy the query in ascending order by document ID. You can specify the sort order for your data using orderBy(), and you can limit the number of documents retrieved using the limit().

But I found the above statement false. I have stored the document ids as increment numbers 1,2,3...

But when I fetched the document IDs by the following code.

firebaseFirestore.collection(documentPathOnFireStore).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                for(DocumentSnapshot documentSnapshot : task.getResult().getDocuments()){
                    documentsIds += documentSnapshot.getId() + ","
                }
         }});

I received the following results

1, 10, 100, 101, 102....

Is there really any way to get the result in ascending order of document Ids?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
beginner
  • 2,366
  • 4
  • 29
  • 53

1 Answers1

2

I received the following results:

1, 10, 100, 101, 102

That's the expected behavior since most likely you're storing those values as strings and not as numbers. Bear in mind that when ordering strings, the order is lexicographical. For example, 10 is placed before 2. See an example below:

1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3

Is there really any way to get the result in ascending order of document Ids?

Yes, the single option that you have is to change the type of the field to be number and not string. Or, check my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hi Alex, Thank you so much for the great explanation! As far as I know, Firestore will always use the document Id as strings. In that case, I would require a new field (Number type) to get the desired results. So in short, it is not possible to do the same with document IDs. Thank you for your help! – beginner May 13 '22 at 12:01
  • Yes, that's correct. You're very welcome. – Alex Mamo May 13 '22 at 12:56