Jonathan
Jonathan

Reputation: 83

In Firestore, how do I change for all documents of a collection of which a certain field has a certain value, that field in a certain value?

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?

Upvotes: 1

Views: 117

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

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");
            }
        }
    }
});

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317362

  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.

Upvotes: 1

Related Questions