How to search array and find user ID in Firestore

512 views Asked by At

Firstly, I am sorry for my terrible english.

I am trying to learn and make a Firestore app. In my app, I get the colors of users. If other users chosen the same color, it matches the users. It is very simple app but I cant write the query and get userId.

My database example:

enter image description here

cRef = fStore.collection("Users");
cRef.whereArrayContains("colors", "red").get();

I have read many articles but could not understand, how can I list the UserId's with this 'whereArrayContains()' method? Thank you for your helpings.

1

There are 1 answers

0
Renaud Tarnec On BEST ANSWER

You should indeed use the array-contains operator to filter based on array values.

In your case you would do something along these lines:

cRef = fStore.collection("Users");

cRef.whereArrayContains("colors", "red")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

More details in the doc here and here.