0

The official Firebase docs explain how to delete a single document. But they do not explain how to delete multiple documents at once.

See: Delete data from Cloud Firestore

One common scenario where the user may want to delete multiple documents, would be for example: Removing all of the items from a user's shopping cart. (But not from other user's carts.)

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Paul Smith
  • 166
  • 3
  • 13
  • If you intend to use a RecyclerView, then I think that this article, [How to delete a record from Firestore on a RecylerView left/right swipe?](https://medium.com/firebase-tips-tricks/how-to-delete-a-record-from-firestore-on-a-recylerview-left-right-swipe-d65d993f0baf) or [How to delete multiple records from Firestore using RecyclerView multi-selection?](https://medium.com/firebase-tips-tricks/how-to-delete-multiple-records-from-firestore-using-recyclerview-multi-selection-96108e4c6166) will help. – Alex Mamo Mar 14 '22 at 13:01

1 Answers1

1

To do this efficiently, you should use a batched write. This allows you to perform multiple delete operations simultaneously.

See: Transactions and batched writes | Firebase Documentation

For example, to delete three documents at once:

WriteBatch batch = db.batch();
batch.delete(db.collection("cartItems").document("item1"));
batch.delete(db.collection("cartItems").document("item2"));
batch.delete(db.collection("cartItems").document("item3"));
batch.commit()
     .addOnSuccessListener((result) -> { 
       Log.i(LOG_TAG, "Selected items have been deleted."); 
     })
     .addOnFailureListener((error) -> { 
       Log.e(LOG_TAG, "Failed to delete selected items.", error); 
     });

So if you know the document Ids in advance, this is fairly simple:

public void removeSelectedItemsFromShoppingCart(List<String> itemIds) {
  WriteBatch batch = db.batch();
  CollectionReference collection = db.collection("cartItems");
  for (String itemId : itemIds) {
    batch.delete(collection.document(itemId));
  }

  batch.commit()
       .addOnSuccessListener((result) -> {
          Log.i(LOG_TAG, "Selected items have been removed.");
        })
        .addOnFailureListener((error) -> {
           Log.e(LOG_TAG, "Failed to remove selected items.", error);
        });
}

But if you don't know the document Ids in advance, you may have to query the database first:

public void removeAllItemsFromShoppingCart(String userId) {
  db.collection("cartItems")
    .whereEqualTo("userId", userId)
    .get()
    .addOnSuccessListener((querySnapshot) -> {
      WriteBatch batch = db.batch();
      for (DocumentSnapshot doc : querySnapshot) {
        batch.delete(doc.getReference());
      }

      batch.commit()
           .addOnSuccessListener((result) -> {
              Log.i(LOG_TAG, "All items have been removed.");
            })
            .addOnFailureListener((error) -> {
               Log.e(LOG_TAG, "Failed to remove all items.", error);
            });
    })
    .addOnFailureListener((error) -> {
       Log.e(LOG_TAG, "Failed to get your cart items.", error);
    });
}

Note that the code above uses a one-time read, instead of a real-time read. Which is critical here, so it doesn't continue deleting documents after the operation is done.

Paul Smith
  • 166
  • 3
  • 13