如何通过传递查询来删除Firestore文档?

时间:2018-04-26 12:24:26

标签: java firebase google-cloud-firestore

我有这个问题:Query queryDelete = firestore.collection("images").whereEqualTo("imageUrl", model.getImageUrl());我希望将其传递给DocumentReference,以便我可以调用这样的内容:docRef.delete.addOnCompleteListener(...) 关于如何做的任何想法?

1 个答案:

答案 0 :(得分:2)

您必须首先获取()文档,然后对其进行迭代并在其上调用delete()。

以下代码来自firestore文档页面:

/** Delete a collection in batches to avoid out-of-memory errors.
 * Batch size may be tuned based on document size (atmost 1MB) and application requirements.
 */
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) {
      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());
  }
}

https://firebase.google.com/docs/firestore/manage-data/delete-data