Home > Software design >  Compare Firestore Array to another Firestore Array with whereArrayContains
Compare Firestore Array to another Firestore Array with whereArrayContains

Time:09-23

I wanted to compare an array value with another array in firestore The code below works as "ingredients" is an array in firestore, and "sugar" is what the ingredients compare to but i want to make "ingredients" compare to my String[] array value 1 by 1 For example if : String[] a = {"sugar","b","c"} , then this should be true String[] b = {"salt","pepper"}, then this will false. I have commented in my code for a more clearer need.

Putting Arrays.asList(test) didnt work. Any solution?

   List<String> ingreList;
   String[] ingredientLists;
   String[] test = {"sugar","b"};


private void checkTesting() {
        postRef.whereArrayContains("ingredients", "sugar" /*PUTTING STRING[] HERE TO COMPARE OR ARRAYLIST STRING IS ALSO FINE TOO (I HAVE BOTH) */)
                .get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        postLists3.clear();
                        for(QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){
                            Post post = documentSnapshot.toObject(Post.class);
                                postLists3.add(post);
                        }
                        postAdapter.notifyDataSetChanged();
                        progressBar.setVisibility(View.GONE);
                    }
                });
    }

CodePudding user response:

You would have to use whereArrayContainsAny as shown below if you want to pass any array instead of a string:

postRef.whereArrayContainsAny("ingredients", Arrays.asList("sugar"))

However do note that this will fetch document where the ingredients field contains at least 1 item in the list passed in whereArrayContainsAny. For example, if the ingredients field in a document has ["sugar", "milk", "water"] and you query with Arrays.asList("sugar"), the document will be returned in query result.


If you want to fetch documents where all the ingredients are included then you might have to store ingredients as a map:

ingredients: {
  sugar: true,
  water: true
}

Then you can add multiple .whereEqualTo("ingredients.[NAME]", true); and query the required documents.

  • Related