Home  >  Article  >  Java  >  How to Delete Firestore Collections and Subcollections Effectively?

How to Delete Firestore Collections and Subcollections Effectively?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 15:30:03454browse

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:

  • Retrieve all documents within the employees and locations subcollections.
  • Delete each retrieved document.
  • Delete the list document.

2. Use the deleteCollection Method (Not Recommended):

  • The Firestore deleteCollection method deletes all documents within a collection recursively.
  • Use this method only for small collections to avoid memory errors.
  • Ensure to execute this operation from a trusted server environment.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn