删除 Firestore 集合中的所有文档 [英] Deleting all documents in Firestore collection

查看:36
本文介绍了删除 Firestore 集合中的所有文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种清除整个集合的方法.我看到有一个批量更新选项,但这需要我知道集合中的所有文档 ID.

I'm looking for a way to clear an entire collection. I saw that there is a batch update option, but that would require me to know all of the document IDs in the collection.

我正在寻找一种方法来简单地删除集合中的每个文档.

I'm looking for a way to simply delete every document in the collection.

谢谢!

下面的答案是正确的,我使用了以下内容:

Answer below is correct, I used the following:

  func delete(collection: CollectionReference, batchSize: Int = 100) {
    // Limit query to avoid out-of-memory errors on large collections.
    // When deleting a collection guaranteed to fit in memory, batching can be avoided entirely.
    collection.limit(to: batchSize).getDocuments { (docset, error) in
      // An error occurred.
      let docset = docset

      let batch = collection.firestore.batch()
      docset?.documents.forEach { batch.deleteDocument($0.reference) }

      batch.commit {_ in
        self.delete(collection: collection, batchSize: batchSize)
      }
    }
  }

推荐答案

没有 API 可以一次性删除整个集合(或其内容).

There is no API to delete an entire collection (or its contents) in one go.

来自 Firestore 文档:

要删除 Cloud Firestore 中的整个集合或子集合,请检索集合或子集合中的所有文档并将其删除.如果您有较大的集合,您可能希望以较小的批次删除文档以避免内存不足错误.重复该过程,直到您删除了整个集合或子集合.

To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them. If you have larger collections, you may want to delete the documents in smaller batches to avoid out-of-memory errors. Repeat the process until you've deleted the entire collection or subcollection.

该文档中甚至还有一个 Swift 示例,因此我建议您尝试一下.

There is even a Swift sample in that documentation, so I recommend you try it.

Firebase CLI 允许您使用单个命令删除整个集合,但它只是调用 API 批量删除该集合中的所有文档.如果这满足您的需求,我建议您查看(稀疏)文档firestore:delete 命令.

The Firebase CLI allows you to delete an entire collection with a single command, but it just calls the API to delete all documents in that collection in batches. If this suits your needs, I recommend you check out the (sparse) documentation for the firestore:delete command.

这篇关于删除 Firestore 集合中的所有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆