How to update a single field of all documents in firestore using flutter?

2,341

Solution 1

As @Doug mentioned there's no direct way, you'll have to query the data, get the DocumentReference from QueryDocumentSnapshot and invoke update on it.

var collection = FirebaseFirestore.instance.collection('collection');
var querySnapshots = await collection.get();
for (var doc in querySnapshots.docs) {
  await doc.reference.update({
    'single_field': 'newValue',
  });
}

Solution 2

Firestore doesn't offer a SQL-like "update where" command that updates everything at once, so you will have to:

  1. Query for the documents to update
  2. Iterate each DocumentSnapshot and get its DocumentReference object using the reference property
  3. For each document, update the field with its new value
Share:
2,341
Steven Mathew
Author by

Steven Mathew

Updated on December 23, 2022

Comments

  • Steven Mathew
    Steven Mathew over 1 year

    I have a 100 user documents in database, and I have to update one field to 0 in all documents. How do we do it?

  • Lojith Vinsuka
    Lojith Vinsuka over 2 years
    Works for me. Thanks :)