0

I have a Cloud Firestore database for transportations:

  • Transportations {collection}
    • TransportationId {document}
      • TransportationName: "Private Transaportation"
      • Cars {collection}
        • CarId {document}
          • CarName: "Taxi"
        • CarId {document}
          • CarName: "Private Taxi"

In Cars collection I have over 100 cars (documents). I cannot find in the documentation nor on stackoverflow how to get all the transportation names in which the CarName name has a specific particular value. How to solve this?

val Taxi = db
    .collection("Transportations").document("TransportationId")
    .collection("Cars").whereEqualTo("CarName", "Private Taxi")

Thanks!

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Johans Bormman
  • 855
  • 2
  • 11
  • 23

1 Answers1

2

The short answer is that you cannot achieve this in Firestore. You cannot query your database for all the cars regardless of which transportation contained them.

But in such cases, there is a workaround in which you should change your database structure a little bit by creating a new top-level collection named cars in which you should add all your car objects. Beheath each car object you'll also should add the desired transportation as a property. In this way you'll be able to query the database according to your needes.

Your database structure should look like this:

Firestore-root
   |
   --- cars (collection)
        |
        --- carId (document)
              |
              --- transportation: "Private Taxi"
              |
              --- //other car details
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • It means that I will have data duplicated. This is not what I want. – Johans Bormman Jul 13 '18 at 14:20
  • *firebaser here* We're aware that querying across multiple (sub)collections in the way you propose, would lead to simpler code and less data duplication. We're considering adding it, but as usual: no promises and definitely no timelines. Duplicating the data as Alex describes is currently the only way to implement this use-case. – Frank van Puffelen Jul 13 '18 at 14:30
  • @FrankvanPuffelen Thank you Puf! – Alex Mamo Jul 13 '18 at 14:45
  • @JohansBormman In addition to Frank's comment, I also recommend you to see this video, [Denormalization is normal with the Firebase Database](https://www.youtube.com/watch?v=vKqXSZLLnHA). Is for Firebase Real-time database but same principles apply in Cloud Firestore. – Alex Mamo Jul 13 '18 at 14:46
  • @FrankvanPuffelen Yes, it will be nicer to write less code :) Thanks! – Johans Bormman Jul 13 '18 at 15:02