TccHtnn
TccHtnn

Reputation: 936

how to order by sub-collection in firestore

I built a data structure in firestore like that:

data1

data2

How to order all documents in cities by the salary of doctor document in Job sub-collections?

Thanks for your help!

Upvotes: 6

Views: 2847

Answers (1)

Ricardo Smania
Ricardo Smania

Reputation: 3139

The documentation says you can't:

Limitations: You can't easily delete subcollections, or perform compound queries across subcollections.

What I would do is create another collection called SalariesByCity or something, that contains:

  • The ID of the city
  • The ID of the job
  • The salary

Then you could first query this collection filtering by the job and ordering by the salary (you will need to create an index for that), and then for each line you can query the City collection by ID to get the city details.

You could also include the city name in this SalariesByCity collection so you wouldn't even need to perform another query. But then you need to always update this collection whenever you update the city. Transactions might be helpful for that.

So your collection could be something like this:

  • The ID of the city
  • The name of the city or even the city object
  • The ID of the job
  • The name of the job
  • The salary

Upvotes: 5

Related Questions