How to delete multiple documents from Cloud Firestore?

18,765

Solution 1

To delete multiple documents, you can do a single batched write. The WriteBatch class has a delete() method for this purpose.

The performance to between a single BatchedWrite and multiple DocumentReference.delete calls is similar though, see here. As in: I expect both of them to be plenty enough efficient for a case where the user selects documents to be deleted. If you find out that this is not the case, share the code that reproduces the performance problem.

Solution 2

FirebaseFirestore db = FirebaseFirestore.getInstance();

WriteBatch writeBatch = db.batch();

for (int i=0;i<cartList.size();i++){
    DocumentReference documentReference = db.collection("Users").document(cartList.get(i).getProductId());
    writeBatch.delete(documentReference);
}

writeBatch.commit().addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        // Do anything here
    }
});

Solution 3

As this is the first result when you search for "how to delete multiple documents on Firestore", I wanted to share a working code snippet that not only does what OP is asking, but also splits your batches into chunks to avoid reaching the limit of 500 commits per batch.

const deleteEmptyMessages = async () => {
  
  const snapshot = await firestore.collection('messages').where('text', '==', '').get();
  const MAX_WRITES_PER_BATCH = 500; /** https://cloud.google.com/firestore/quotas#writes_and_transactions */

  /**
   * `chunk` function splits the array into chunks up to the provided length.
   * You can get it from either:
   * - [Underscore.js](https://underscorejs.org/#chunk)
   * - [lodash](https://lodash.com/docs/4.17.15#chunk)
   * - Or one of [these answers](https://stackoverflow.com/questions/8495687/split-array-into-chunks#comment84212474_8495740)
   */
  const batches = chunk(snapshot.docs, MAX_WRITES_PER_BATCH);
  const commitBatchPromises = [];

  batches.forEach(batch => {
    const writeBatch = firestore.batch();
    batch.forEach(doc => writeBatch.delete(doc.ref));
    commitBatchPromises.push(writeBatch.commit());
  });

  await Promise.all(commitBatchPromises);
};

Solution 4

I used batched writes for this. For example I deleted all documents, where the field "text" is empty:

const emptyMessages = await firestore.collection('messages').where("text", "==", "").get()
const batch = firestore.batch();
emptyMessages.forEach(doc => {
    batch.delete(doc.ref);
});
await batch.commit();
Share:
18,765

Related videos on Youtube

Michał Wolny
Author by

Michał Wolny

Updated on June 15, 2022

Comments

  • Michał Wolny
    Michał Wolny about 2 years

    What's the best way to delete many (not all) documents from Cloud Firestore?

    The official documentation contains information regarding deleting one document and all documents: https://firebase.google.com/docs/firestore/manage-data/delete-data.

    • Doug Stevenson
      Doug Stevenson over 6 years
      How have you measured the efficiency?
    • Michał Wolny
      Michał Wolny over 6 years
      Haven't measured yet, but isn't performing one query more efficient than performing many (e.g. 100) queries?
    • Doug Stevenson
      Doug Stevenson over 6 years
      A delete isn't a query. Until you have evidence to substantiate your claim, I don't think there's anything Stack Overflow can do for you. Don't make assumptions about how the client SDK works.
    • Michał Wolny
      Michał Wolny over 6 years
      Maybe I put a wrong question. It should be: what's the best way to delete many (not all) documents from Cloud Firestore?
    • Doug Stevenson
      Doug Stevenson over 6 years
      The API you're given allows you to delete documents individually.
    • Jay
      Jay over 6 years
      If you asked the wrong question or need to add additional info, please update your question as adding it in the comments may be overlooked.
  • Michał Wolny
    Michał Wolny over 6 years
    Hi Frank, thanks for the answer, but I've optimized my code and deleting documents individually is sufficient.
  • Paul Smith
    Paul Smith over 2 years
    Deleting them in a batch allows you to implement error handling with a single handler though. It also makes easy to perform actions after all selected documents have been deleted.