Home > Blockchain >  In Firestore, how do I change for all documents of a collection of which a certain field has a certa
In Firestore, how do I change for all documents of a collection of which a certain field has a certa

Time:07-29

I want to change the value of a certain field of all documents in a Cloud Firestore collection to a certain value if that field is equal to a certain value. How do I do that?

CodePudding user response:

  1. Query with a filter that matches all of the documents you want to chage.
  2. Iterate the results of that query.
  3. Update each document with the new field value it should contain.

CodePudding user response:

In addition to Doug's answer, if you want to update all documents in a collection where a field contains a certain value, then please use the following lines of code:

FirebaseFirestore db = FirebaseFirestore.getInstance();
Query query = db.collection("collName").whereEqualTo("fieldName", "fieldValue");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                document.getReference().update("fieldToUpdate", "value");
            }
        }
    }
});
  • Related