更新 Firestore 集合中找到的所有文档中的字符串字段

基本上,我想知道是否可以更新 Firestore 集合中的所有文档。我可以像这样获取列表中的所有文档:


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

        }

    }

});

但是,我似乎无法一次更新所有文档或这些文档中的类似字符串。如果上述方法是不可能的,那么就更新所有文档而言,有什么办法可以解决。


猛跑小猪
浏览 177回答 3
3回答

波斯汪

Raj 的方法会起作用,但可能会导致进行大量写入。正如 Doug 所提到的,您可能喜欢批量写入。void getData() {&nbsp; &nbsp; mFirebaseFirestore.collection("Events").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onComplete(@NonNull Task<QuerySnapshot> task) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (task.isSuccessful()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<String> list = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (QueryDocumentSnapshot document : task.getResult()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.add(document.getId());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d(TAG, list.toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; updateData(list); // *** new ***&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d(TAG, "Error getting documents: ", task.getException());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}void updateData(ArrayList list) {&nbsp; &nbsp; // Get a new write batch&nbsp; &nbsp; WriteBatch batch = db.batch();&nbsp; &nbsp; // Iterate through the list&nbsp; &nbsp; for (int k = 0; k < list.size(); k++) {&nbsp; &nbsp; &nbsp; &nbsp; // Update each list item&nbsp; &nbsp; &nbsp; &nbsp; DocumentReference ref = db.collection("Events").document(list.get(k));&nbsp; &nbsp; &nbsp; &nbsp; batch.update(ref, "field_you_want_to_update", "new_value");&nbsp; &nbsp; }&nbsp; &nbsp; // Commit the batch&nbsp; &nbsp; batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onComplete(@NonNull Task<Void> task) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Yay its all done in one go!&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}文档:https : //firebase.google.com/docs/firestore/manage-data/transactions#batched-writes

宝慕林4294392

没有一个操作可以根据某些搜索条件更新多个文档。您必须像现在一样迭代查询结果,然后单独更新每个文档。您也可以使用事务或批量写入以原子方式执行更新,但这不会让您阻止迭代初始查询结果中的所有文档。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java