[英]keeping a running total of documents field in Firebase based upon the day of month
I have Firebase collection of MeterReading which store electricity readings, here is what it look likes, suppose i have 3 records in collection 2 with date of 12 and 1 with date of 20 as following我有 Firebase 的 MeterReading 集合,它存储电力读数,这是它的样子,假设我在集合 2 中有 3 条记录,日期为 12,1 条记录的日期为 20,如下所示
meter_no : "A112"
reading : 6000
time : 12 May 2020 at 04:45:20 UTC+5
meter_no : "A112"
reading : 500
time : 12 May 2020 at 07:45:20 UTC+5
meter_no : "A134"
reading : 800
time : 20 May 2020 at 04:45:20 UTC+5
now i want to list down sum of reading per day as in our case (sum of readings of date 12 and sum of readings of date 20).现在我想像我们的案例一样列出每天的读数总和(日期 12 的读数总和和日期 20 的读数总和)。 How should i query this problem?
我应该如何查询这个问题?
In Firestore, you cannot perform complex queries, since it's not built for that, so you could do this in 2 ways (Since you did not specify a language I will give examples in Javascript):在 Firestore 中,您不能执行复杂的查询,因为它不是为此而构建的,因此您可以通过两种方式执行此操作(因为您没有指定语言,我将在 Javascript 中给出示例):
var snapshotAfter = await db.collection("readings")
.where("time", ">=", "12 May 2020 at 00:00:00 UTC+5")
.get()
.catch(function(error) {
console.log("Error getting documents: ", error);
});
var snapshotBefore = await db.collection("readings")
.where("time", "=<", "13 May 2020 at 00:00:00 UTC+5")
.get()
.catch(function(error) {
console.log("Error getting documents: ", error);
});
var list = [];
snapshotAfter.forEach(function(docAfter) {
snapshotBefore.forEach(function(docBefore) {
if(docAfter == docBefore){
list.push(docAfter);
}
});
});
var sum = list.length;
I find this code quite complex and not very efficient, the better solution would be the above.我发现这段代码非常复杂而且效率不高,更好的解决方案是上面的。
If you change you firebase structure to add a have a date field and an array of reading it will make it simpler to query, it could be something like this:如果您更改 firebase 结构以添加一个日期字段和一个读取数组,它将使查询更简单,它可能是这样的:
date: 12 May 2020 at 00:00:00 UTC+5
readingsArray: [
{
meter_no : "A112"
reading : 6000
time : 12 May 2020 at 04:45:20 UTC+5
},
{
meter_no : "A112"
reading : 500
time : 12 May 2020 at 07:45:20 UTC+5
}
]
date: 20 May 2020 at 00:00:00 UTC+5
readingsArray: [
{
meter_no : "A134"
reading : 800
time : 20 May 2020 at 04:45:20 UTC+5
}
]
And you can query your data by simply doing this:您只需执行以下操作即可查询您的数据:
var snapshot = await db.collection("readings")
.where("date", "==", "12 May 2020 at 00:00:00 UTC+5")
.get()
.catch(function(error) {
console.log("Error getting documents: ", error);
});
var sum = snapshot.docs[0].readingsArray.length;
So, in summary, it really depends on where you want to add complexity, the code or the db.因此,总而言之,这实际上取决于您想在何处添加复杂性、代码或数据库。
NOTE : All of this code is an untested example so you might have to refine it, but should be a good starting point.注意:所有这些代码都是未经测试的示例,因此您可能需要改进它,但这应该是一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.