Home > database >  Firestore Query Default Order
Firestore Query Default Order

Time:05-14

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?

CodePudding user response:

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:

  • Related