"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Effectively Delete Collections and Subcollections in Firestore?

How to Effectively Delete Collections and Subcollections in Firestore?

Published on 2024-11-03
Browse:565

 How to Effectively Delete Collections and Subcollections in Firestore?

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:

  1. Retrieve all documents within the "employees" subcollection and delete them.
  2. Repeat the process for the "locations" subcollection.
  3. Finally, delete the "listId" document.

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 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 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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3