0

Is it possible to query a Firestore collection to get all documents whose array filed has a specific prefix word?

for example,

User A uid : uid000 region list : [ USA-CA, USA-NY]

User B uid : uid001 region list : [ USA-ALL, EU-FR]

User C uid : uid002 region list : [ASIA-JP, ASIA-CH]

when fetching the user list like above from Firestore and select 'USA-' to filter, I want to get all users whose region list even has an element that starts with 'USA-'

result : userlist : [ User A, User B ]

1 Answer 1

2

when fetching the user list like above from Firestore and selecting 'USA-' to filter, I want to get all users whose region list even has an element that starts with 'USA-'

No, you cannot achieve that using an array. However, if you're allowed to change the database structure a little bit, then you can achieve the same result. Since the USA- is the common element of those arrays, then you should consider naming the array like so:

Firestore-root
   |
   --- users (collection)
        |
        --- uid000 (document)
        |    |
        |    --- USA: ["CA", "NY"]
        |
        --- uid001 (document)
        |    |
        |    --- USA: ["ALL"]
        |    |
        |    --- EU: ["FR"]
        |
        --- uid002 (document)
             |
             --- ASIA: ["JP", "NY"]

To query the users who have the USA array present in the document, please use the following lines of code:

FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("products").whereNotEqualTo("USA", null).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());
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

As you can see we query against the USA field for existence. The result in the logcat will be:

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

3 Comments

Nice answer Alex.
Hi Alex long time no see. I have a new question! Could u please check this and give me answer??

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.