1

I have group collection. In each group document, I store which users are associated with the group via members array field in firebase.

Eg: user1 & user2 are in xyz(id) group and I would like to query from client to get all the group where having user1 & user2 ( not OR ). I have tried firebase IN array query but it returns empty results. Is there is a way to query using AND, I am making chat application with react native.

My Code (Not Working:)

firestoreRef.collection('group').where('members','in',[ id_of_user1, id_of_user2 ]).get(); // return empty array

1 Answer 1

1

To begin with, with the current firebase capability, what you want to do is impossible. I'm sure you have read it already, but here is the documentation of firestore's array related queries, and none of them support AND operation.

With that being said, it is a bit of a hack, but I have done something similar to what you want to do.

You would make a field that combines all of the users' uids in single string, and you query with that field.

For example, let's say you have the following two users:

user1
uid: 'abc'

user2
uid: 'def'

Then in their group document, you create a field, let's call this memberKey for now and store their combined user ids as a single string:

{
  'memberKey': 'abcdef'
}

Now you can query the group at which user1 and user2 are in by combining their uids on the client to get the target document.

But there is one problem here. How do you know which uid comes first? How do you know it's 'abcdef' and not 'defabc'? Well, that easy. You just have to sort the list of uids alphanumerically. This way, you will always have consistent memberKey.

You can even expand this method to more than 2 users too.

I know this is not a very pretty solution that you were hoping for, but with firestore's current limitation, we are forced to get clever like this.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect solution, yes I already added member-key as you mention, and stack on which id come first and query the key, sorting will save my life, thank you so much for your support.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.