2

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?

Steven Mathew
  • 21
  • 1
  • 2

3 Answers3

8

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',
  });
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
4

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
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

Try doing the following

  1. Query the documents to update
  2. Go through each DocumentSnapshot and get its DocumentReference object using the reference property and for each document, update the field with its new value
    void updateNotificationCount() async {
        FirebaseUser _currentUser = await FirebaseAuth.instance.currentUser();
        String authid = _currentUser.uid;
        var snapshots =
            activityFeedRef.document(authid).collection('feedItems').snapshots();
        try {
          await snapshots.forEach((snapshot) async {
            List<DocumentSnapshot> documents = snapshot.documents;
    
            for (var document in documents) {
              await document.reference.updateData(<String, dynamic>{
                'seen': true,
              });
            }
          });
        } catch (e) {
          print(e.toString());
        }
      }

The code above simply updates all unread notification from false to true immediately the user clicks on the notification tray

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
devDonald
  • 1
  • 2