'How to delete multiple documents from a collection in Cloud Firestore? [duplicate]

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.)



Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1