0

Is it possible in Firestore to delete some documents, where the "Value Name" is the same?

For example: I have some UID's as Documents inside a Collection. Inside these Documents will be saved two types of "Value Names". 1st "Value Name" is called "byCar". 2nd "Value Name" is called "byFoot". Now I want to delete all Documents, where the "Value Name" is equal to "byCar". All other documents, where the "Value Name" is "byFoot" will be untouched. Is something like this possible?

I program in Flutter / Dart and it would be awesome, if someone could provide me an answer, because I was not able to find somthing on the internet.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

2

Firestore doesn't support update queries, where you send a query to the server and it updates (or in your case deletes) all matching documents. To write or delete a document you will need to know its entire path in your application code.

So that means you need to perform two steps to delete the documents:

  1. Execute a query to find all documents matching your condition.
  2. Loop over the results and delete them.

In code that'd be something like:

refUser.where("city", isEqualTo: "CA").getDocuments().then((querySnapshot){
  for (DocumentSnapshot documentSnapshot in querySnapshot.documents){
    documentSnapshot.reference.delete();
  });
  snapshot.documents.first.reference.delete();
});

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you very much. I understand, thats maybe the reason why I was not able to finde something on the Internet haha. I will try it out. :) –  Jan 23 '21 at 17:54
  • I included some links I found by searching for "updating multiple documents" here on Stack Overflow. – Frank van Puffelen Jan 23 '21 at 18:05
  • Thanks again, I see that my search request was wrong... –  Jan 23 '21 at 20:31
  • Sorry, I guess I wrote a little bit of a mess. I meant, that I have searched for the wrong thing on the internet, so I was not able to find a solution by my own. Thank you for your time and help! :) –  Jan 25 '21 at 13:53
0

Your code would look something like this:

QuerySnapshot querySnapshot = await db
  .collection("yourPathCollection")
  .where("Value Name", isEqualTo: "byCar")
  .get()
  .then((querySnapshot) {
querySnapshot.docs.forEach((doc) {
  doc.reference.delete();
});
return null; });

Perhaps Cloud Firestore will block your request, so you will need to change your database rules, according to your need.

Lucas Baggio
  • 378
  • 1
  • 4
  • 12
  • Thank you very much, I guess I have looked for something like your code. I will try out and will write later if its worked. :) –  Jan 23 '21 at 20:30
  • I already tested this code in a similar example and it worked, if it works for you, please mark this answer as useful :) – Lucas Baggio Jan 23 '21 at 21:45
  • 1
    I marked your answer and thank you for your help! :) –  Jan 25 '21 at 13:51