FireStore 批量写入不同的集合

jha*_*ane 3 android firebase google-cloud-firestore

是否有另一种方法可以对属于各种集合的多个文档执行一组写入?

有点像官方文档中的对多个文档进行批量写入。

FireStore 文档上的事务和批量写入

举个例子;

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));
Run Code Online (Sandbox Code Playgroud)

是否可以对不同的集合执行批量写入?

Fra*_*len 5

批量操作可以跨集合进行。来自批量写入的文档

// 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) {
        // ...
    }
});
Run Code Online (Sandbox Code Playgroud)

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