【问题标题】:Android Firestore query get the id of the document that contains the value in the searchAndroid Firestore查询获取包含搜索值的文档的id
【发布时间】:2018-10-20 04:52:09
【问题描述】:

Firestore database image

您好,我刚刚尝试使用 Firestore。我在获取文档 ID 时遇到了一些问题。

问题是,我想得到一个包含值(蓝色框)的文档 ID(红色框)。

我使用以下查询:

collection("mychannel").whereEqualTo("74wRU4xHrcV9oWAXEkKeRNp41c53")

但是没有给出结果。

谢谢!

【问题讨论】:

    标签: android firebase kotlin google-cloud-firestore


    【解决方案1】:

    这里回答了这个问题:Firestore: Query by item in array of document

    总之,不要使用数组在 Firestore 中存储数据,因为您尝试执行的查询尚不可用(请记住,它仍处于测试阶段)。您应该改用地图。

    【讨论】:

      【解决方案2】:

      official documentation

      虽然 Cloud Firestore 可以存储数组,it does not support 查询数组成员或更新单个数组元素。

      所以没有办法可以使用以下查询:

      collection("mychannel").whereEqualTo("74wRU4xHrcV9oWAXEkKeRNp41c53")
      

      如果您只想获取整个 userId 数组,则需要像这样遍历 Map

      collection("mychannel").document("1fReXb8pgQvJzFdzpkSy").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
          @Override
          public void onComplete(@NonNull Task<DocumentSnapshot> task) {
              if (task.isSuccessful()) {
                  DocumentSnapshot document = task.getResult();
                  if (document.exists()) {
                      Map<String, Object> map = document.getData();
                      for (Map.Entry<String, Object> entry : map.entrySet()) {
                          if (entry.getKey().equals("userId")) {
                              Log.d("TAG", entry.getValue().toString());
                          }
                      }
                  }
              }
          }
      });
      

      但请注意,即使 userId 对象作为数组存储在数据库中,entry.getValue() 也会返回 ArrayList,而不是 array

      所以输出将是:

      [74wRU4xHrcV9oWAXEkKeRNp41c53]
      

      如果您考虑这种替代数据库结构,更好的方法将是,其中每个用户 ID 都是地图中的键,所有值都是 true:

      userId: {
          "74wRU4xHrcV9oWAXEkKeRNp41c53": true,
          "AdwF...": true,
          "YsHs...": true
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-10
        相关资源
        最近更新 更多