2

I have a Firestore database set up where I have a Users collection and Animals collection (these animals can be created by users at any time). For a particular user, I want to grab a random animal document that the user hasn't seen yet.

I don't believe it is possible to query for non-existing keys in Firestore, which makes this problem non-trivial for me. Is there a better way to do this than to have a dictionary of all animal ids for each user? My issue with that approach would be scalability since animals can be created by users and thus every user's animal dictionary would have to be updated per new animal.

Thanks for any help in advance!

eforkin
  • 107
  • 1
  • 1
  • 9

1 Answers1

1

You won't be able to do this with a single query that returns a single document.

There is no sense of randomness in Firestore queries. If you want something random, you'll have to select that in your code from a set of items in memory. This means, at the very least, you're going to have to first figure out how to query for all the animals a user hasn't seen yet, then select randomly from that set in application code.

You are correct in assuming that you'll need some sort of collection that records who has seen what animal, then query that for a list of unseen animals. Then you can randomly select from that the final animal document.

An in order to do that, you're going to need another collection of documents that record who has seen what animal previously.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441