How to delete multiple documents with specific Value in Firestore with Flutter

Viewed 1510

I'm trying to delete multiple docs whith a specific String value in a Field from my collection. But im doing something wrong I think.

onPressed: () async {
  Firestore.instance.collection('collection').getDocuments().then((snapshot) {
  for (DocumentSnapshot ds in snapshot.documents.where(('field') == 'specificValue'){
    ds.reference.delete();
    });
  });
}

Im currently trying to delete each Item with a loop after getting all documents, but im not able to delecte the specific Items. Because I'm getting an error under the "where" part.

1 Answers

To use where, you'll need to get the list of all the docs in that collection, then where to filter the List and delete the filteredList

  onPressed: () async {
    onPressed() async {
    Firestore.instance.collection('collection').getDocuments().then((snapshot) {
      List<DocumentSnapshot> allDocs = snapshot.documents;
      List<DocumentSnapshot> filteredDocs =  allDocs.where(
              (document) => document.data['field'] == 'specificValue'
      ).toList();
      for (DocumentSnapshot ds in filteredDocs){
        ds.reference.updateData({
          'field': 'newValue'
        });
      }
    });
  }
Related