Firebase Cloud Firestore Many to Many Relationships

InfoStatus picture InfoStatus · Oct 8, 2017 · Viewed 9.8k times · Source

How to structure and query data from Firebase Cloud Firestore in a many to many relationship?

I have Companies and Contractors. A Contractor can work for more than one Company and a Company can have multiple Contractors. This is a straightforward many to many relationship. I want to be able to answer the questions about Companies and Contractors:

Given a Company, who are the current Contractors. Given a Contractor what Companies are they working for. What is the right way for structuring the data within Cloud Firestore?

Answer

André Lima picture André Lima · Feb 15, 2018

You can have Contractors item with a map field which has the key as the company key and the value can be true ou a timestamp to help ordering. And Companys with a map field with the contractors key as the key and some value. This aproach is mentioned in https://firebase.google.com/docs/firestore/solutions/arrays, when you try to filter and sort toghether...

Contractors
  companies
    idCompany1: timestamp
    idCompany2: timestamp
    idCompany3: timestamp

Companies
  contractors
    idContractor1: timestamp
    idContractor2: timestamp

Is this case you can make any queries like this company contractors or the companies of this contractor. Like this:

fireStore.collection("Companies").whereField("contractors." + idContractor, isGreaterThan: 0).order(by: "contractors." + idContractor, descending: true)

Yes you have to update both places in any task

Hope this helps!