Deleting Collections and Subcollections in Firestore
Firestore does not provide a direct method for deleting entire collections or subcollections. However, there is a workaround that involves deleting the individual documents within the collection or subcollection.
Modeling Data Structure
The provided data structure is suitable for the given use case. It is not necessary to restructure the database to delete specific lists.
Steps for Deleting a Collection or Subcollection
To delete an entire collection or subcollection, follow these steps:
Batch Processing (Optional)
For larger collections, consider deleting documents in batches to avoid memory issues.
Security and Performance Implications
Firestore discourages large delete operations due to potential negative security and performance impacts. Perform these operations cautiously, particularly from untrusted environments.
Implementation Code for Android
<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 Entire Collections and Subcollections in Firestore?. For more information, please follow other related articles on the PHP Chinese website!