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:
- Query with a filter that matches all of the documents you want to chage.
- Iterate the results of that query.
- 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");
}
}
}
});