0

I'm looking for a way to filter one Firestore collection based on if the UID exists in another collection. I used the term antijoin but really any way of excluding records that dont exist in both. The structure of my firestore is as follows:

. 
|- /Users
    |- /User_A
        |- Message UID 001
        |- Message UID 002
        |- ...
    |- /User_B
    |- ...
|- /Messages
    |- Message UID 001
    |- Message UID 002
    |- ...

Id like for a way to filter a query of "/Messages" to exclude those under /User_X (depending on who is logged in). Right now my approach is to query both from /Users/User_X and from /Messages and filter within my code but Im hoping there's a way to avoid transporting mostly unnecessary data especially when it becomes a large collection.

BejanSadeghian
  • 609
  • 1
  • 6
  • 10

1 Answers1

1

Firestore reads and queries always operate on a single collection, or collection group (collections with the exact same name). They can never work (or return documents) across multiple collections.

So if you want to filter the documents from one collection on a value that is in another collection, you will need to replicate the value into each of the documents in the former collection.

In your use-case you could do a not in query, but only after first reading all documents from User_A and extracting the IDs. And even then the not-in condition can only include 10 values. So most likely you're better off:

  • either reading all messages and excluding the ones the user has already seen client-side.
  • or duplicating the messages for each user, and then tracking in their own copy whether they've seen each message or not.
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you @frank. I’m also considering using a sub collection to track if a user has seen that message. It’s good to know that I’m not missing something entirely so thank you. https://stackoverflow.com/questions/46573014/firestore-query-subcollections/46573167#46573167 – BejanSadeghian Nov 14 '20 at 17:03