如何从Cloud Firestore中删除多个文档?

时间:2018-01-09 19:18:18

标签: firebase google-cloud-firestore

从Cloud Firestore删除许多(不是全部)文档的最佳方法是什么?

官方文档包含有关删除一个文档和所有文档的信息:https://firebase.google.com/docs/firestore/manage-data/delete-data

4 个答案:

答案 0 :(得分:6)

要删除多个文档,您可以执行单个batched write。为此目的WriteBatch class has a delete() method

我希望单个BatchedWrite和多个DocumentReference.delete来电之间的效果非常相似。如下所示:我希望在用户选择要删除的文档的情况下,它们都足够高效。如果您发现情况并非如此,请共享再现性能问题的代码。

答案 1 :(得分:1)

因为这是您搜索“如何在 Firestore 上删除多个文档”时的第一个结果,所以我想分享一个工作代码片段,它不仅可以满足 OP 的要求,还可以拆分将批次分成块以避免达到 500 commits per batch 的限制。

const deleteEmptyMessages = async () => {
  
  const snapshot = await firestore.collection('messages').where('text', '==', '').get();
  const MAX_WRITES_PER_BATCH = 500; /** https://cloud.google.com/firestore/quotas#writes_and_transactions */

  /**
   * `chunk` function splits the array into chunks up to the provided length.
   * You can get it from either:
   * - [Underscore.js](https://underscorejs.org/#chunk)
   * - [lodash](https://lodash.com/docs/4.17.15#chunk)
   * - Or one of [these answers](https://stackoverflow.com/questions/8495687/split-array-into-chunks#comment84212474_8495740)
   */
  const batches = chunk(snapshot.docs, MAX_WRITES_PER_BATCH);
  const commitBatchPromises = [];

  batches.forEach(batch => {
    const writeBatch = firestore.batch();
    batch.forEach(doc => writeBatch.delete(doc.ref));
    commitBatchPromises.push(writeBatch.commit());
  });

  await Promise.all(commitBatchPromises);
};

答案 2 :(得分:0)

FirebaseFirestore db = FirebaseFirestore.getInstance();

WriteBatch writeBatch = db.batch();

                for (int i=0;i<cartList.size();i++){
                    DocumentReference documentReference = db.collection("Users").document(cartList.get(i).getProductId());
                    writeBatch.delete(documentReference);
                }

                writeBatch.commit().addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        // Do anything here
                    }
                });

希望有帮助

答案 3 :(得分:0)

为此我使用了批量写入。例如我删除了所有文档,其中“文本”字段为空:

            const emptyMessages = await firestore.collection('messages').where("text", "==", "").get()
            const batch = firestore.batch();
            emptyMessages.forEach(doc => {
                batch.delete(doc.ref);
            });
            await batch.commit();

希望对大家有所帮助