How to create/update multiple documents at once in Firestore

后端 未结 4 1180
忘掉有多难
忘掉有多难 2020-12-01 12:00

Is it possible to store multiple documents in Firestore with only one request? With this loop it\'s possible but this would cause one save operation per item in the list.

4条回答
  •  北海茫月
    2020-12-01 12:27

    From Firebase documentation :

    You can also execute multiple operations as a single batch, with any combination of the set(), update(), or delete() methods. You can batch writes across multiple documents, and all operations in the batch complete atomically.

    // 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() {
        @Override
        public void onComplete(@NonNull Task task) {
            // ...
        }
    });
    

    Firestore multiple write operations

    Hope it helps..

提交回复
热议问题