1

My firestore database design

My db design is above picture. I wanna create a query which returns user where tags are matched. But i didnt any solution to query.

This is my flutter code:

enter image description here

But it doesnt work. How can i query array of map of document?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
emowise
  • 121
  • 1
  • 14

1 Answers1

1

The courses is an array and not a map so you cannot use the dot notation to query. If the courses is made a collection (or a sub-collection) on it's own then you would be able to query users easily:

users -> {userId}
(col)     (doc)

courses -> {courseId}
(col)        (doc)

You would have to include a field userId in each course document which would be used to identify which user owns that course.

await firestore.collection("courses").where("tags", arrayContainsAny: tagKeys)

This will return all courses where the tags array contains at least 1 item in the tagKeys list. If you need exact match i.e. all the tags in tagKeys must be present in Firestore document then you would have to restructure the database as mentioned in this answer.


Fetching all matching documents might not be ideal since you just need user IDs that matches the tags. In that case you can store a field which contains tags from all the courses in a single array field in the user document.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • I need user info to show course on the list. If i create new collection as "courses" and search course according to tag list, then do i need to create queries to get users which have that courses? – emowise Sep 19 '21 at 11:56
  • @emiled if you want to query users who have a specific course, it'll be best to store an array `course_tags` which will contains tags of all the courses that a user has. – Dharmaraj Sep 19 '21 at 11:58