0
votes

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: "[email protected]"
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.

1
@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
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

1 Answers

4
votes

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.