如何对Firebase Firestore中的节点求和? [英] How to Sum nodes in firebase firestore?
问题描述
我正在制作用于订购比萨饼的应用程序.
I am making app for ordering pizza.
就像您在图片上看到的那样,我想从每个文档中获取所有名为"ukupno"的键值,并将其求和为最终价格.
Like you see on image i want to take all key values named "ukupno" from each document and Sum it for final price.
这是我获取购物车数据的方式:
This is how i fetch cart data:
this.cartService.getCart(this.user.Uid).subscribe(res => {
this.cart = res.map(i => {
return {
...i.payload.doc.data(),
id: i.payload.doc.id
};
});
});
}
getCart(uid) {
return this.firestore
.collection("cart/")
.doc(uid)
.collection("/ubaceno")
.snapshotChanges();
}
推荐答案
对于集合的所有文档,基本上有两种方法可以汇总文档字段的值:
There are basically two ways to sum up the value of a document field for all documents of a collection:
1/查询整个集合,遍历结果(即 snapshotChanges()
.
1/ Query for the entire collection, loop over the result (i.e. the querySnapshot
), e.g. with forEach()
, and sum all the field values in the loop. To do that with angularfire2 you would probably use snapshotChanges()
.
但是,如果您的馆藏中包含很多文档,这不是很有效,而且在您的馆藏中每个文档需要花费一个文档读取.
However, If your collection contains a lot of documents, this is not very efficient and moreover it will cost one document read per document in your collection.
2/使用一些分布式计数器 保持所有文档的最新金额.要实现此方法,您每次在 ubaceno
集合中创建/修改/删除文档时都必须更新计数器,将 ukupno
字段的值添加或减去/从柜台.
2/ Use some Distributed counters to keep an up-to-date sum for all your documents. To implement this approach, you have to update the counter each time you create/modify/delete a document in the ubaceno
collection, adding or subtracting the value of the ukupno
field to/from the counter.
您可以通过具有一组在创建/修改/删除时更新计数器的云函数,或者通过在前端的写入/修改/删除代码中集成计数器更新的事务来做到这一点.
You could do that either by having a set of Cloud Functions that update the counters upon Creation/Modification/Deletion, or by integrating in your write/modify/delete code in your front end the transaction for the counter update.
这篇关于如何对Firebase Firestore中的节点求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!