Is There A Way To Query For A Firestore Collection To Get The Number Of Times A Field's Value Occurs?
Solution 1:
There are different possible approaches:
1. Fetch all documents with field TransmitterError == true
You can write a query that will return all the documents and use the size
property of the QuerySnapshot
:
db.collection("Londiani Hill").where("TransmitterError", "==", true)
.get()
.then(function(querySnapshot) {
console.log(querySnapshot.size);
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
The problem with this approach is that you read all the documents with a field TransmitterError = true
each time you want to count them and this has a cost.
2. Maintain a counter
You can increment a counter each time you create a document with field TransmitterError = true
(and decrement it if you delete the doc or change the value of TransmitterError
to false
). You will need to maintain one counter per collection.
For implementing the counter you can either use a Distributed counter per collection OR use one "counter" document per collection where you have a counter field that you increment with firebase.firestore.FieldValue.increment()
, see the doc.
The selection criteria between the two types of the counter is the number of times a counter for a specific collection will be updated: as a matter of fact, in Cloud Firestore, you can only update a single document about once per second. So if you know that counter's documents might be updated more than once per second, you should choose the distributed counters approach, otherwise, you can rely on one counter document per collection.
Solution 2:
Might this help you to solve problem
db.collection("Londiani Hill").where("TransmitterError", "==", true).get().then(function(querySnapshot) {
console.log(querySnapshot.size);
});
Post a Comment for "Is There A Way To Query For A Firestore Collection To Get The Number Of Times A Field's Value Occurs?"