Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create/update multiple documents at once in Firestore

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.

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) } 
like image 286
Marcel Bochtler Avatar asked Oct 07 '17 09:10

Marcel Bochtler


People also ask

How do you update multiple documents on firestore?

Firestore doesn't have the ability to bulk update documents without knowing their IDs. You will have to somehow know the document ID of each document to update (perform a query, or do batches of queries), and update each one individually.

Can firestore update multiple documents matching a condition using one query?

Cloud Firestore does not support the equivalent of SQL's update queries.

How do you update an array in firestore?

// Atomically remove a region from the "regions" array field. # Atomically add a new region to the 'regions' array field. # // Atomically remove a region from the 'regions' array field. # Atomically add a new region to the 'regions' array field.


2 Answers

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

Firestore multiple write operations

Hope it helps..

like image 192
Yassin Avatar answered Sep 20 '22 12:09

Yassin


Update some properties on all documents in a collection:

resetScore(): Promise<void> {   return this.usersCollectionRef.ref.get().then(resp => {     console.log(resp.docs)     let batch = this.afs.firestore.batch();      resp.docs.forEach(userDocRef => {       batch.update(userDocRef.ref, {'score': 0, 'leadsWithSalesWin': 0, 'leadsReported': 0});     })     batch.commit().catch(err => console.error(err));   }).catch(error => console.error(error)) } 
like image 45
jsaddwater Avatar answered Sep 20 '22 12:09

jsaddwater