Basically, I would like to know if it is possible to update all of the documents found in a collection in Firestore. I am able to get all the documents in a list like so:
<In order to update all the documents in a collection first you have have to retrieve all of them in a List and then iterate that list and update them. Here is a sample code:-
for (int k = 0; k < list.size(); k++) {
firestore.collection("Events").document(list.get(k))
.update("Key", value).addOnSuccessListener(new OnSuccessListener<Void>()
{
@Override
public void onSuccess(Void aVoid) {
Log.i("Update", "Value Updated");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(MainActivity.this, "Error In Updating Details: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Raj's method will work but may lead to doing a lot of writes. As Doug mentioned, you may like to do it in a batch write.
void getData() {
mFirebaseFirestore.collection("Events").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
Log.d(TAG, list.toString());
updateData(list); // *** new ***
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}
void updateData(ArrayList list) {
// Get a new write batch
WriteBatch batch = db.batch();
// Iterate through the list
for (int k = 0; k < list.size(); k++) {
// Update each list item
DocumentReference ref = db.collection("Events").document(list.get(k));
batch.update(ref, "field_you_want_to_update", "new_value");
}
// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// Yay its all done in one go!
}
});
}
Documentation: https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes
There is no single operation that will update multiple documents based on som search criteria. You will have to iterate the query results as you're doing now, then individually update each of the documents. You could possibly also use a transaction or batch write to perform the updates atomically, but that will not let you prevent iterating all the documents in the initial query result.