In Java 11, I have a function that makes multiple MongoDb .countDocuments(query) calls on the same collection with 3 different queries. Is there a way to aggregate these three calls into one request so that the MongoDB service isn't called 3 separate times. I'm currently using Bson and the com.mongodb.client.model.Filters.* library to build the queries individually. However I haven't found a good resource on how to do this with BSON and I am open to other methods to accomplish this.
My function includes something like this..
import org.springframework.data.mongodb.core.MongoOperations;
private final MongoOperations mongoOperations;
public RequestCount Foo (){
Bson query1 = eq("field1", "foo" )
Bson query2 = eq("field2", "bar" )
Bson query3 = eq("field3", "raw" )
count1 = mongoOperations.getCollection("collection").countDocuments(query1);
count2 = mongoOperations.getCollection("collection").countDocuments(query2);
count3 = mongoOperations.getCollection("collection").countDocuments(query3);
return RequestCount(count1, count2, count3);
}
I then store these in an Standard PoJo object with 3 private fields like...
public class RequestCount {
private Integer count1;
private Integer count2;
private Integer count3;
}