Reputation: 19
strucrure enter image description here
I need to get data from the "Income" field, which is in each document in collection "values", and write them to array to calculate the sum of the elements of this array.
Upvotes: 1
Views: 982
Reputation: 83068
Do as follows if you want to sum up the values. You don't need an array.
var totalIncome = 0;
db.collection("values").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
totalIncome += doc.data().Income;
});
console.log(totalIncome);
});
Be aware however that it will cost a document read for each document of the collection. If your values
collection contains a lot of documents, you may use another strategy like updating the totalIncome on documents creation/deletion.
If you really need to populate an array, do as follows:
var totalIncomeArray = [];
db.collection("values").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
totalIncomeArray.push(doc.data().Income);
});
//Do whatever you want with the array: it contains all the Income values
});
Upvotes: 2