【问题标题】:Firestore firebase Android search and update queryFirestore firebase Android 搜索和更新查询
【发布时间】:2019-04-22 01:30:35
【问题描述】:

我正在尝试更新 FireBase Firestore 中我的集合中现有文档的一个字段。我想使用其中一个字段来搜索该文档。 我的收藏名称是“投诉”, 我的文档结构看起来像 --

complainant_Name: "XYZ"
complaint_Details : "some random details"
e_Mail: "xyz@gmail.com"
id: 5
phone_No: "1234567890" 

我想搜索文档,如果文档的“id”字段是 5,我想更新它说将“complainant_Name”字段更改为“ABC”。如何在java android中编写此查询的代码?在 Firebase Firestore 中搜索后,我找不到任何说明如何更新的代码源。

【问题讨论】:

  • 我想,这会对你有所帮助stackoverflow.com/questions/34537369/…
  • @ATIKFAYSAL 您提供的链接解释了如何在 Firebase 实时数据库中执行此操作,而 OP 要求使用不同的产品 Cloud Firestore。
  • 我想查询 Firebase Firestore ,而不是 Firebase 实时数据库。您提供的链接适用于 Firebase 实时数据库。而且我也想更新(不仅仅是链接中提到的搜索)。

标签: android firebase google-cloud-firestore


【解决方案1】:

要解决这个问题,请使用以下代码行:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference complaintsRef = rootRef.collection("complaints");
complaintsRef.whereEqualTo("id", 5).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                Map<Object, String> map = new HashMap<>();
                map.put("complainant_Name", "ABC");
                complaintsRef.document(document.getId()).set(map, SetOptions.merge());
            }
        }
    }
});

使用此代码后,属性complainant_Name 将保存ABC 的值。

【讨论】:

  • 谢谢!! rootRef.coolection("complaints") 的一个小错误;应该是 rootRef.collection("complaints");
  • @AdiAzarya 感谢您的错字;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-28
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 2020-08-28
相关资源
最近更新 更多