Sorting Firestore Documents

Is there any possible way I can order the Cloud Firestore documents of a collection based on a number at a value of a specific field. For example in the collection ids there are documents and in each one there is a field called idNumber. The value of that idNumber is 0 then in the next document is 1 then 2 etc. Is it possible?

Thanks in advance!

Answer

Is it possible?

Yes it is! To order the documents within a collection by a specific numeric property, please use the following query:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference idsRef = rootRef.collection("ids");
Query query = idsRef.orderBy("idNumber", Query.Direction.ASCENDING);

This query will order your documents according to the idNumber property ascending. If you want a reverse order just change the direction to DESCENDING. That’s it!

Edit:

According to the official documentation of Query’s orderBy(String field) method:

Creates and returns a new Query that’s additionally sorted by the specified field.

And according to Query’s orderBy(String field, Query.Direction direction) method:

Creates and returns a new Query that’s additionally sorted by the specified field, optionally in descending order instead of ascending.