问题描述
我正在使用 Cloud Firestore 并且有一系列文档.对于集合中的每个文档,我想更新其中一个字段.
I'm using Cloud Firestore and have a collection of documents. For each document in the collection I would like to update one of the fields.
使用事务来执行更新效率低下,因为我在更新数据时不需要读取任何数据.
Using a transaction to perform the update would be inefficient because I do not need to read any of the data while updating it.
批量更新似乎是正确的方向,但是文档不包括一次更新多个文档的示例.请参见此处:批量写入
Batch updates seem like the right direction, however the docs do not include examples of updating multiple docs at once. See here: Batched Writes
推荐答案
如果您使用过 Firebase 数据库,则不可能以原子方式写入完全单独的位置,这就是您必须使用批量写入的原因,这意味着要么所有操作成功,或者都不应用.
If you have used Firebase database, writing to completely single separate locations atomically was not possible, that's why you would have to use batch writes, which means that either all of the operations succeed, or none of them are applied.
关于 Firestore,所有操作现在都以原子方式处理.但是,您可以将多个写入操作作为包含 set()、update() 或 delete() 操作的任意组合的单个批处理来执行.一批写入原子完成,可以写入多个文档.
Regarding Firestore, all operations are now atomically processed. However, you can execute multiple write operations as a single batch that contains any combination of set(), update(), or delete() operations. A batch of writes completes atomically and can write to multiple documents.
这是一个关于写入、更新和删除操作的批处理操作的简单示例.
This a simple example regarding a batch operation for write, update and delete operation.
WriteBatch batch = db.batch();
DocumentReference johnRef = db.collection("users").document("John");
batch.set(johnRef, new User());
DocumentReference maryRef = db.collection("users").document("Mary");
batch.update(maryRef, "Anna", 20); //Update name and age
DocumentReference alexRef = db.collection("users").document("Alex");
batch.delete(alexRef);
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// ...
}
});
在批处理对象上调用 commit()
方法意味着您提交了整个批处理.
Calling commit()
method on the batch object means that you commit the entire batch.
这篇关于如何在 Firestore 中进行批量更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!