1

Firestore database image

Hello, I just tried to use Firestore. I had some problem when getting document id.

The question is, I want to get a document id (red box) which has value (blue box) in it.

I use the following query:

collection("mychannel").whereEqualTo("74wRU4xHrcV9oWAXEkKeRNp41c53")

But did not give results.

Thanks!

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Fathur Radhy
  • 27
  • 1
  • 6

2 Answers2

3

As in the official documentation:

Although Cloud Firestore can store arrays, it does not support querying array members or updating single array elements.

So there is no way in which you can use the following query:

collection("mychannel").whereEqualTo("74wRU4xHrcV9oWAXEkKeRNp41c53")

If you only want to get the entire userId array you need to iterate over a Map like this:

collection("mychannel").document("1fReXb8pgQvJzFdzpkSy").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Map<String, Object> map = document.getData();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    if (entry.getKey().equals("userId")) {
                        Log.d("TAG", entry.getValue().toString());
                    }
                }
            }
        }
    }
});

But note, even if userId object is stored in the database as an array, entry.getValue() returns an ArrayList, not an array.

So the output will be:

[74wRU4xHrcV9oWAXEkKeRNp41c53]

A better approach will be if you consider this alternative database structure, where each user id is the key in a map and all values are true:

userId: {
    "74wRU4xHrcV9oWAXEkKeRNp41c53": true,
    "AdwF...": true,
    "YsHs...": true
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
1

This question is answered here: Firestore: Query by item in array of document

In summary, don't use arrays to store data in Firestore as the query you are trying to do is not available yet (remember it is still in beta). You should use a Map instead.

DAA
  • 1,346
  • 2
  • 11
  • 19