Home >Java >javaTutorial >How to Delete Firestore Collections and Subcollections Effectively?
Deleting Collections and Subcollections in Firestore
Problem Statement:
In a Firestore database with a collection of lists, each list contains two subcollections: employees and locations. When a user wishes to delete a specific list, deleting the list document alone does not remove the subcollections. This issue arises due to the Firestore documentation's indication that deleting a document with subcollections does not automatically remove those subcollections.
Proposed Solutions:
1. Delete Subcollections Iteratively:
2. Use the deleteCollection Method (Not Recommended):
Android Code for Recursive Deletion:
The following Android code demonstrates how to recursively delete a collection:
<code class="java">private void deleteCollection(final CollectionReference collection, Executor executor) { Tasks.call(executor, () -> { int batchSize = 10; Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize); List<DocumentSnapshot> deleted = deleteQueryBatch(query); while (deleted.size() >= batchSize) { DocumentSnapshot last = deleted.get(deleted.size() - 1); query = collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize); deleted = deleteQueryBatch(query); } return null; }); } @WorkerThread private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception { QuerySnapshot querySnapshot = Tasks.await(query.get()); WriteBatch batch = query.getFirestore().batch(); for (DocumentSnapshot snapshot : querySnapshot) { batch.delete(snapshot.getReference()); } Tasks.await(batch.commit()); return querySnapshot.getDocuments(); }</code>
The above is the detailed content of How to Delete Firestore Collections and Subcollections Effectively?. For more information, please follow other related articles on the PHP Chinese website!