首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java中完全删除集合(包括文档子集合)

如何在java中完全删除集合(包括文档子集合)
EN

Stack Overflow用户
提问于 2022-10-12 01:56:08
回答 1查看 38关注 0票数 0

我只是像下面这样修改了一些正式的示例片段

代码语言:javascript
复制
    static void deleteCollection(CollectionReference collection, int batchSize) {
    try {
        // retrieve a small batch of documents to avoid out-of-memory errors
        ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
        int deleted = 0;
        // future.get() blocks on document retrieval
        List<QueryDocumentSnapshot> documents = future.get().getDocuments();
        for (QueryDocumentSnapshot document : documents) {

            //delete subcollections
            Iterable<CollectionReference> collections =
                    document.getReference().listCollections();
            for (CollectionReference collRef : collections) {
                deleteCollection(collRef, batchSize);
            }
            //delete document
            document.getReference().delete();
            ++deleted;
        }
        if (deleted >= batchSize) {
            // retrieve and delete another batch
            deleteCollection(collection, batchSize);
        }
    } catch (Exception e) {
        System.err.println("Error deleting collection : " + e.getMessage());
    }
}

但是这个代码对我不起作用。文档子集合保持原样。这里怎么了?谢谢你的回答

EN

回答 1

Stack Overflow用户

发布于 2022-10-12 02:39:57

只是为某人分享正确的代码

代码语言:javascript
复制
private static void deleteCollection(CollectionReference collection, int batchSize) {
    try {
        // retrieve a small batch of documents to avoid out-of-memory errors
        ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
        int deleted = 0;
        // future.get() blocks on document retrieval
        List<QueryDocumentSnapshot> documents = future.get().getDocuments();
        for (QueryDocumentSnapshot document : documents) {

            //delete document
            document.getReference().delete();
            ++deleted;
            //delete subcollections
            Iterable<CollectionReference> collections =
                    document.getReference().listCollections();
            for (CollectionReference collRef : collections) {
                deleteCollection(collRef, batchSize);
            }

        }
        if (deleted >= batchSize) {
            // retrieve and delete another batch
            deleteCollection(collection, batchSize);
        }
    } catch (Exception e) {
        System.err.println("Error deleting collection : " + e.getMessage());
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74035696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档