如何使用where子句删除Firestore数据库中集合中的文档?

时间:2019-11-02 02:00:45

标签: android firebase google-cloud-firestore

我使用下面的代码来引用一个特定的文档,我需要使用集合中的“ where”子句删除该文档,但是我无法弄清楚执行该操作的功能,因此我在android java和firestore中使用了该文档数据库

private void deleteDocument() {
        final CollectionReference docref = (CollectionReference) db.collection("users").document(CommentAuthorId).collection("notifications_received").whereEqualTo( "comment_id", Comment_Id );

      docref.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
          @Override
          public void onComplete(@NonNull Task<QuerySnapshot> task) {
              if (task.isSuccessful()) {

                  for (QueryDocumentSnapshot document : task.getResult()) {

                      Log.d(TAG, document.getId() + " => " + document.getData());

                  }
              } else {
                  Log.d(TAG, "Error getting documents: ", task.getException());
              }
          }
      });
    }

3 个答案:

答案 0 :(得分:1)

Firestore不提供像SQL那样根据某些过滤器删除文档的“删除位置”功能。

您要做的是查询所有文档并对其进行遍历(就像现在一样),然后使用快照getReference()中提供的引用分别删除每个文档:

for (QueryDocumentSnapshot document : task.getResult()) {
    document.getReference().delete();
}

答案 1 :(得分:0)

试试看,它对我有用:

 holder.imgCross.setOnClickListener(v -> {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setTitle("Do you want to Delete News  in your list");
        alertDialog.setPositiveButton("CANCEL", (dialog, which) -> dialog.cancel());
        alertDialog.setNegativeButton("YES", (dialog, which) -> {

            FirebaseFirestore.getInstance().collection("NewsAndNotification").document(newsandNotiModel.getId())
                    .delete().addOnSuccessListener(aVoid -> {
                notifyDataSetChanged();
            });

          /*  Toast.makeText(context, "Added in SOS list", Toast.LENGTH_SHORT).show();*/

        });
        AlertDialog dialog = alertDialog.create();
        dialog.show();
    });

答案 2 :(得分:0)

您应该能够在文档参考本身上调用delete方法。