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.
To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them. If you have larger collections, you may want to delete the documents in smaller batches to avoid out-of-memory errors.
In order to delete multiple entries from your database, you need to know all those locations (refernces). So with other words, in the way you add data, you should also delete it. This method atomically deletes all those entries.
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.
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
}
});
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With