Fairly new to MongoDB and working on a simple project. Currently trying to make pie charts using counts of certain fields:value. What I have currently works but for some fields that have multiple possible values creating the chart take a very long time due to the iteration in Java. I’m thinking that MongoDB can do more of this work on its end. This what I’m doing currently:
Create the dataset for JFreeChart piechart.
private PieDataset getCreditsDataset() {
DefaultPieDataset dataset = new DefaultPieDataset();
String key = "Current Credits";
for (int i = 0; i < 131; i++) {
int value = i;
double total = 0;
try {
total = sda.getIntTotal(key, value);
} catch(NullPointerException npe) {
//do nothing
}
if (total != 0) {
dataset.setValue(String.valueOf(value), total);
} else {
//do not add
}
}
return dataset;
}
Get count of value for key
public double getIntTotal(String key, int value) {
String field = "$" + key;
Document doc = collection.aggregate(
Arrays.asList(
Aggregates.match(Filters.eq(key, value)),
Aggregates.group(field, Accumulators.sum("count", 1))
)
).first();
return (double) doc.getInteger("count", 0);
}
Iterating like this takes quite a bit of time and I think MongoDB should be able to do more the work and reduce time but I don’t know how to structure the query. Is it possible for MongoDB to perform this count operation and return a document with the all of the results? Any help is appreciated.