FireStore批量写入不同集合

时间:2018-07-01 18:41:42

标签: android firebase google-cloud-firestore

是否有另一种方法可以对属于多个 Collections 的多个文档执行一组写操作?

在多个 文档 中像官方文档一样对批处理写入进行排序。

Transactions and batched writes on FireStore Docs

对于实例;

WriteBatch batch = db.batch();

// Set the value of 'NYC' in 'cities' collection

DocumentReference nycRef = db.collection("cities").document("NYC");
batch.set(nycRef, map1);


// Set the value of 'ABC' in 'SomeOtherCollection' collection

DocumentReference otherRef = db.collection("SomeOtherCollection").document("ABC");
batch.set(otherRef,map2));

有可能在不同集合上执行批量写入吗?

1 个答案:

答案 0 :(得分:1)

批处理操作可以跨集合进行。来自documentation on batched writes

// Get a new write batch
WriteBatch batch = db.batch();

// Set the value of 'NYC'
DocumentReference nycRef = db.collection("cities").document("NYC");
batch.set(nycRef, new City());

// Update the population of 'SF'
DocumentReference sfRef = db.collection("cities").document("SF");
batch.update(sfRef, "population", 1000000L);

// Delete the city 'LA'
DocumentReference laRef = db.collection("cities").document("LA");
batch.delete(laRef);

// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        // ...
    }
});

由于您传递了要写入batch.set()的文档,因此您也可以将文档从不同的集合传递给每个调用。