Updating a string field in all documents found in a collection in Firestore

不问归期 提交于 2020-01-30 11:17:46

问题


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:

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());
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

But, I cant seem to be able to update all documents, or similar strings within those documents at once. If the above is not possible, what could be a work around as far as to update all the documents.


回答1:


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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/52088433/updating-a-string-field-in-all-documents-found-in-a-collection-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!