Reputation: 41
I am studying Firestore with React. After I added the array data into the firestore, I am trying to count the certain element in array of data in the document. Like the picture I attached, there are several documents includes array data. I want to count the number of CS 34800 in class array from all documents. What is the best way to get it? Thank you!
Upvotes: 0
Views: 3603
Reputation: 317392
There are no counting or aggregating operations on Firebase, so that way you have it now, you will have to query for all the documents that match your criteria, then count the number of documents in your result set.
You can use an "array_contains" operator to get all the documents where an array contains some value.
collectionRef.where("class", "array-contains", "CS 34800").get()
.then(querySnapshot => {
const count = querySnapshot.size
});
If you need to get a count without making a query for documents, you'll have to maintain that yourself for every string that you could possibly need to count, which is an entirely different problem.
Upvotes: 3