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?
Asked
Active
Viewed 3,653 times
3 Answers
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:
- Query for the documents to update
- Iterate each DocumentSnapshot and get its DocumentReference object using the reference property
- For each document, update the field with its new value

Doug Stevenson
- 297,357
- 32
- 422
- 441
0
Try doing the following
- Query the documents to update
- Go through each
DocumentSnapshot
and get itsDocumentReference
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