如何在Firestore中一次创建/更新多个文档

问题描述:

仅有一个请求是否可以将多个文档存储在Firestore中? 使用此循环有可能,但这会导致列表中每个项目的一次保存操作。如何在Firestore中一次创建/更新多个文档

for (counter in counters) { 
    val counterDocRef = FirebaseFirestore.getInstance() 
      .document("users/${auth.currentUser!!.uid}/lists/${listId}/counters/${counter.id}") 
    val counterData = mapOf(
      "name" to counter.name, 
      "score" to counter.score, 
    ) 
    counterDocRef.set(counterData) 
} 

从火力地堡文档:

您也可以执行多个操作作为单一批次,与设定(),更新(的任意组合),或删除()方法。您可以跨多个文档批量写入,并且批量中的所有操作都以原子方式完成。

// 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) { 
     // ... 
    } 
}); 

Firestore multiple write operations

希望它可以帮助..

+0

是的,这正是我一直在寻找,可惜错过了文档。 –

+1

是否有批量读取的方式,类似于这种写入能力,即如果我有10个文档引用,我可以批量获取它们吗?谢谢! – Shaun

+0

@MarcelBochtler在文档中没有提到批处理操作被计为单个读取。批量处理是自动执行操作的一种方式(全部一次或根本不执行),但这与计费不同。我在答案中引用的结算页面明确指出:“您需要为使用Cloud Firestore执行的每个文档读取,写入和删除操作负责。” –