질문
기본적으로 Firestore의 컬렉션에서 찾은 모든 Document를 업데이트 할 수 있는지 알고 싶습니다. 다음과 같이 목록에있는 모든 Document를 가져올 수 있습니다.
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());
}
}
});
그러나 모든 Document 또는 해당 Document 내의 유사한 문자열을 한 번에 업데이트 할 수없는 것 같습니다. 위의 방법이 가능하지 않은 경우 모든 Document를 업데이트하는 한 해결 방법이 될 수 있습니다.
답변1
Raj의 방법은 작동하지만 많은 쓰기 작업으로 이어질 수 있습니다. Doug가 언급했듯이 일괄 쓰기로 수행하는 것이 좋습니다.
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!
}
});
}
Document : https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes
답변2
컬렉션의 모든 Document를 업데이트하려면 먼저 목록에서 모든 Document를 검색 한 다음 해당 목록을 반복하고 업데이트해야합니다. 다음은 샘플 코드입니다.
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
som 검색 기준에 따라 여러 Document를 업데이트하는 단일 작업은 없습니다. 지금하는 것처럼 쿼리 결과를 반복 한 다음 각 Document를 개별적으로 업데이트해야합니다. 트랜잭션 또는 일괄 쓰기 를 사용하여 업데이트를 수행 할 수도 있습니다. 그러나 초기 쿼리 결과에서 모든 Document를 반복하는 것을 방지 할 수는 없습니다.
출처 : https://stackoverflow.com/questions/52088433/updating-a-string-field-in-all-documents-found-in-a-collection-in-firestore