【问题标题】:How to delete a document in collection in firestore database using where clause?如何使用where子句删除firestore数据库中的集合中的文档?
【发布时间】:2019-11-02 02:00:45
【问题描述】:

我使用下面的代码来引用我需要在集合中使用“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());
              }
          }
      });
    }

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

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

    您需要做的是查询所有文档并迭代所有文档(就像您现在一样),然后使用getReference() 提供的快照中的引用单独删除每个文档:

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

    【讨论】:

      【解决方案2】:

      试试这个它对我有用:

       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();
          });
      

      【讨论】:

      • 不,请再次检查,我指的是集合并使用 where 子句过滤集合,并且过滤器仅匹配必须删除的文档
      • 无法传递文档 ID,但我知道该方法,但根据场景,我需要我提到的解决方案
      【解决方案3】:

      您应该能够在文档引用本身上调用删除方法。

      【讨论】:

      • 不,请再次检查,我指的是集合并使用 where 子句过滤集合,并且过滤器仅匹配必须删除的文档
      • 您可以尝试将 ref 获取到 collection("notifications_received"),然后在您的 querysnapshot for 循环中检查您的给定条件,然后删除符合您条件的文档。
      • 我请你举个例子,因为我找不到任何特定的参考资料,我将非常感激
      • 试试 docref.update("comment_id", FieldValue.delete);我认为即使您不使用 whereEqualTo() 也可以这样做,因为它会遍历所有名为“comment_id”的字段并删除它的值。
      猜你喜欢
      • 2018-04-21
      • 2020-11-28
      • 2019-03-18
      • 2020-09-17
      • 2021-01-07
      • 2018-07-20
      • 1970-01-01
      • 2020-02-17
      相关资源
      最近更新 更多