1

I have structured my data in Firebase such that I have a collection of 'users' and each user has various fields as well as a 'skillsIndustry' Array field which contain Maps items (that have fields 'experience' and 'industry').

enter image description here

Now I would like to query my collection of users so that I can ask for all users that have worked in 'Airlines' with experience code of >= 1

Is this possible at all? Or do I have to create sub collections and then use Collection Group Queries?

Many thanks

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Marcel
  • 2,148
  • 6
  • 31
  • 48

1 Answers1

3

No, this is not possible. You can use array-contains to query for the entire object, as explained in this SO answer, but not to query with > or <.

You could create a subcollection, but you can probably find a solution based on the duplication of the data in the same document, which is a common approach in the NoSQL world.

For example, you could have some extra fields named airlinesExperience, shippingExperience, etc. Then you use the skillsIndustry Array field when you want to display all the skills and years of experience, but you use the xxxExperience fields when you want to query.


Another possibility would be to use a map of key/value pairs like

key = "Airlines" / value = 1

key = "Shipping" / value = 3

Then you can query with:

  firebase
    .firestore()
    .collection('users')
    .where('skillsIndustry.Shipping', '>', 2)
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • 2
    Some additional info to add to this: If you ever want to query "users who have **no** shipping experience", you would need to store a value of `0` for `skillsIndustry.Shipping` because if a field in a document doesn't have a value, it won't be added to its index. If `1`/`2`/`3` correspond to some enum (such as `little experience`, `some experience`, and so on) you should space out the values some more and use `10`/`20`/`30` (commonly larger like `100`/`200`/`300`/etc) which gives you the flexibility to insert new levels without having to rewrite every document in your database. – samthecodingman May 13 '21 at 13:18