0

Here is my current DB structure, I have a collection store all the survey question documents, and under each question doc, it has an Answers sub-collection that stores all the users who answered the question. The challenging part is that how do I randomly load 8 questions that are not answered by a specific user, without query the entire question collection? What is the least costly approach? Any suggestions are helpful. Thanks

Below are my Db structure:

enter image description here

enter image description here

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

2 Answers2

3

The best option that you have is to store all question IDs you have in your application into a document in an array data type. If you are worried about the 1 MiB limitation, then you should consider sharding the IDs over multiple documents.

Every time a user answers 8 questions, add those IDs in an array in the User object.

The challenging part is that how do I randomly load 8 questions that are not answered by a specific user, without query the entire question collection?

To load 8 random questions, all you have to do is to download both arrays and remove from the question IDs all the IDs the users already answered. In this way, you'll only have an array of question IDs the user didn't answer. Get other 8 IDs, add them to the User object, and so on.

Remember also that you also need to keep the data in sync, meaning that each time you add a new question, add to the array as well. Do it for the delete operation too.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

You should store the ids of the questions the user has answered in the user data. Then you can just query enough docs that don't match those ids by using a where clause. https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection

jmargolisvt
  • 5,722
  • 4
  • 29
  • 46
  • Are you suggesting you store question ids in an array under the user data? I thought about it, but how scaleable is this approach due to the 1MB doc size limt... – Junjie Yang Aug 28 '21 at 17:32
  • Yes, that is my suggestion. I'm no expert, but I've used Firebase for a while and this is how I'd structure it. It is scalable up to the data limit, so if that's not enough for you, maybe save the data in a more scalable data structure like a map. – jmargolisvt Aug 28 '21 at 19:32