'How to get specific field value from document

I'm trying to get values from documents in collection using Firestore.

This is my code and console log:

 useEffect(() => {
    let totalarray = [];
   firebase.firestore().collection("users").doc(uid).collection("services").get().then((snapshot) => {
     snapshot.forEach((doc) => {
       const obj = doc.data();
       //obj.forEach((data) => totalarray.push((data)) )
      console.log("------->",obj);
     })
   })
  }, [])

This is my Console Log:

Console Log

My Goal is to take the value of each "serviceCost" field for each doc, sum it up and then put it in a global variable for my use.



Solution 1:[1]

If you mean that you would like to get just some parts of Firestore documents then you cannot. you have to read the whole document then do your calculations client side. other method, you may consider creating another collection like "totals". this collection will be populated by Firebase functions that invokes upon document creation and calculate the new cost then added it to the collection "totals"

Solution 2:[2]

I guess I'm late but after some extensive research, there is a way in which we can fetch specific fields from firestore. We can use the select keyword, you're query would be somthing like (I'm using a collection for a generalized approach):

const result = await firebase.firestore().collection("users").select("serviceCost").get();

Where we can access the result.docs to further retrieved the returned filtered result. Thanks!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Methkal Khalawi
Solution 2 Shahzaib Ayyub