Reputation: 53
I'm totally new to Flutter and Firebase. I need some help with Firestore collection groupby and count.
I have a list of names in a collection and what I would like to achieve is to list them by unique values and count the total for each value.
Example:
List of names:
My collection/result should return something like below with unique name and the total count for each value assigned to a variable.
How can I achieve this in Flutter with Firestore?
Upvotes: 0
Views: 2488
Reputation: 2258
You can count names by fetching data with a query and then distinguish them using map like below code.
var map = Map();
_countNames() {
Firestore.instance
.collection("collectionNameHere")
.getDocuments()
.then((snapshot) {
snapshot.documents.map((element) {
if (!map.containsKey(element.data['name'])) {
map[element.data['name']] = 1;
} else {
map[element.data['name']] += 1;
}
}).toList();
});
}
print(map);
Upvotes: 4