user10217645
user10217645

Reputation:

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!

Upvotes: 4

Views: 15199

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

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.

Upvotes: 7

kAliert
kAliert

Reputation: 768

You can order the fields of a collection like this:

CollectionReference idsRef = db.collection("ids");
idsRef.orderBy("idNumber");

For further reading see: docs

Upvotes: 0

Related Questions