0

I am trying to update a field of existing document in my collection in FireBase Firestore. I want to search that document using one of its field. My collection name is "complaints", My document's structure looks like --

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

I want to search documents and if "id" field of a document is say 5, I want to update it say change "complainant_Name" field to "ABC". How to write the code for this query in java android? I couldn't find any code source which tells how to update after searching in Firebase Firestore.

Ankit Selwal
  • 3
  • 1
  • 3
  • I think, this will help you https://stackoverflow.com/questions/34537369/how-to-search-for-a-value-in-firebase-android] – ATIK FAYSAL Nov 19 '18 at 16:36
  • @ATIKFAYSAL You provided a link that explains how to do this in Firebase realtime database while the OP is asking for Cloud Firestore, which is a different product. – Alex Mamo Nov 19 '18 at 16:43
  • I want to query on Firebase Firestore , not Firebase realtime database. The link you are providing is for the Firebase realtime database. And also I want to update as well (not only search as mentioned in link). – Ankit Selwal Nov 19 '18 at 16:49

1 Answers1

4

To solve this, please use the following lines of code:

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

After using this code, the property complainant_Name will hold the value of ABC.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193