且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Firestore中进行批量更新

更新时间:2023-11-25 20:47:16

如果您使用过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.