Jorn
Jorn

Reputation: 272

How to sort data in Firestore according to a property?

I have a database full with cars. The JSON format is this:

docId: {
        "city": "Amsterdam"
        ... other properties
   }

The docId is a key generated by the add function.

I query the database like so:

db.collection("EU-CARS").whereEqualTo("city", "Amsterdam");

And I get all cars that are available in Amsterdam but I want to get something like this:

Amsterdam
    docId
    docId
Utrecht
    docId
    docId

Each city with the corresponding cars. How to solve this without creating a query for each city?

Upvotes: 1

Views: 2405

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

You should use orderBy(), see https://firebase.google.com/docs/firestore/query-data/order-limit-data and https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Query.html#orderBy(java.lang.String)

So you would do:

db.collection("EU-CARS").orderBy("city")

You will get the following

docId1
   city: Amsterdam
   ...
docId2
   city: Amsterdam
   ...
docId3
   city: Utrecht
   ...
docId4
   city: Utrecht
   ...

and it will be up to you to transform that, in your front-end, to the exact format you are looking for.

Upvotes: 3

Related Questions