[英]Multiple collections in 1 batched write firestore
I want to update documents from multiple collections using 1 batched write in Firestore.我想在 Firestore 中使用 1 个批量写入更新来自多个 collections 的文档。 How can I achieve this?
我怎样才能做到这一点? I've seen in Firestore documentation that we can update multiple documents at once using batched write, but how about updating multiple documents in multiple collections at once?
我在 Firestore 文档中看到我们可以使用批量写入一次更新多个文档,但是一次更新多个 collections 中的多个文档怎么样?
This is what I tried so far, but it is not working,到目前为止,这是我尝试过的方法,但没有用,
//Update in User and Monitoring collections
List<WriteBatch> writeBatches = new ArrayList<>();
List<Task<Void>> tasks = new ArrayList<>();
writeBatches.add(db.batch());
List<DocumentSnapshot> documentSnapshotList = task.getResult().getDocuments();
writeBatches.get(batchIndex).update(db.collection("User").document(userId), userMap);
counter++;
for(DocumentSnapshot document : documentSnapshotList){
Monitoring monitoring = document.toObject(Monitoring.class);
if(counter == 499){
tasks.add(writeBatches.get(batchIndex).commit());
writeBatches.add(db.batch());
counter = 0;
batchIndex++;
}
writeBatches.get(batchIndex)
.update(db.collection("Monitoring").document(monitoring.getId()), monitoringMap);
counter++;
}
Tasks.whenAllSuccess(tasks)
.addOnCompleteListener(new OnCompleteListener<List<Object>>() {
@Override
public void onComplete(@NonNull Task<List<Object>> task) {
helper.dismissProgressDialog();
if(task.isSuccessful()){
Toast.makeText(EditUserDetailsActivity.this, "Success", Toast.LENGTH_SHORT).show();
resetFields();
counter = 0;
batchIndex = 0;
Intent intentforBackButton = NavUtils.getParentActivityIntent(EditUserDetailsActivity.this);
intentforBackButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
NavUtils.navigateUpTo(EditUserDetailsActivity.this, intentforBackButton);
}else{
Toast.makeText(EditUserDetailsActivity.this, "Failed", Toast.LENGTH_SHORT).show();
Log.e("App Error", task.getException().getMessage());
}
}
});
As Doug commented, there is nothing special that is required to write to multiple collections in a batched write or transaction.正如 Doug 评论的那样,在批量写入或事务中写入多个 collections 没有什么特别的要求。
So if you'd want to write the same data to another collection int he same batched write, that can be done with:因此,如果您想将相同的数据写入另一个集合 int 他同一批写入,可以通过以下方式完成:
writeBatches.get(batchIndex)
.update(db.collection("Monitoring").document(monitoring.getId()), monitoringMap);
writeBatches.get(batchIndex)
.update(db.collection("AnotherCollection").document(monitoring.getId()), monitoringMap);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.