Home > database >  Array field Firestore query with prefix
Array field Firestore query with prefix

Time:10-03

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 ]

CodePudding user response:

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
  • Related