Delete a Collection or Subcollection in Firestore
When dealing with nested data structures in Firestore, deleting a collection can be tricky due to the limitations of collection deletion. This article provides a solution for deleting both collections and subcollections while maintaining the data structure.
In the presented scenario, there is a collection called "lists" containing documents with IDs representing list IDs. Each list document has two subcollections: "employees" and "locations." Deleting a specific list requires careful handling to avoid orphaning subcollections.
Deletion Process
To successfully delete a specific list, follow these steps:
Batch Deletion for Large Collections
For large collections, it is advisable to delete documents in batches to avoid memory errors. Implement a function that deletes documents in a batch of 10 and repeats the process until the entire collection is deleted.
Firestore Security Implications
It's important to note that the Firebase team recommends against deleting collections. However, for small collections and in trusted server environments, this approach can be used with caution.
Code Example for Android
For Android applications, you can utilize the following code to 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 a Collection or Subcollection in Firestore while Maintaining Data Structure?. For more information, please follow other related articles on the PHP Chinese website!