Skip to content

Firestore Transactions and Batched Writes

Eoin Landy edited this page Jan 30, 2020 · 2 revisions

The contents of this page are based on the original Firebase Documentation

Batched Writes

If you do not need to read any documents in your operation set, you can execute multiple write operations as a single batch that contains any combination of set(), update(), or delete() operations. A batch of writes completes atomically and can write to multiple documents.

Batched writes are also useful for migrating large data sets to Cloud Firestore. A batched write can contain up to 500 operations and batching operations together reduces connection overhead resulting in faster data migration.

Batched writes have fewer failure cases than transactions and use simpler code. They are not affected by contention issues, because they don't depend on consistently reading any documents. Batched writes execute even when the user's device is offline. The following example shows how to build and commit a batch of writes:

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

// Set the value of 'NYC'
var nycRef:DocumentReference = db.collection("cities").document("NYC");
batch.setData({}, nycRef);

// Update the population of 'SF'
var sfRef:DocumentReference = db.collection("cities").document("SF");
batch.updateData({"population": 1000000 }, sfRef);

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

batch.commit(function(error:FirestoreError):void{

});
Clone this wiki locally