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

1,081

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'
        });
      }
    });
  }
Share:
1,081
Kinnay
Author by

Kinnay

Updated on December 23, 2022

Comments

  • Kinnay
    Kinnay over 1 year

    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.

  • Kinnay
    Kinnay over 3 years
    Hey, your function works great. But i noticed that it would be better to set the value "filed" to null for each document, instead of deleting them. Is it possible to do this with a updateData() function instead of the delete() function? When yes how can i only uopdate this one Field Value.
  • JideGuru
    JideGuru over 3 years
    Ohh 'filed' is a type. it's meant to be 'field'