如何在Firestore中进行批量更新 [英] How to do a bulk update in Firestore

查看:88
本文介绍了如何在Firestore中进行批量更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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中进行批量更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆