Deleting Collections and Subcollections in Firestore
When working with Firestore, scenarios may arise where you need to delete collections or subcollections. However, deleting the parent document that houses the subcollections presents challenges. This article addresses how to manage such situations effectively.
Database Structure and Deletion Problem
Consider a scenario with a collection called "lists," where each document represents a list with its unique ID. Each list document has subcollections named "employees" and "locations." The structure is as follows:
(lists) -listId (employees) (locations)
If a user wishes to delete a specific list, deleting the "listId" document will retain its subcollections, defying Firestore's documentation.
Solution: Sequential Deletion
To address this, we propose a sequential deletion approach:
This method ensures the complete removal of the specific list and its associated subcollections.
Considerations
While deletion is an effective tool, Firebase recommends using it cautiously, especially for large collections. However, for smaller collections, deletion is a viable option. If using deletion for large collections is unavoidable, execute it on a trusted server environment.
Code Implementation for Android
For Android applications, you can use the following code to implement the deletion process:
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(); }
This code retrieves and deletes documents in batches, ensuring the deletion of both the collection and its subcollections.
The above is the detailed content of How to Effectively Delete Collections and Subcollections in Firestore?. For more information, please follow other related articles on the PHP Chinese website!