Count and Aggregation Statistics in mongodb Fragmented Cluster

  java, question

Under mongodb fragmented clusters, it is not accurate to use count statistics directly, but it is possible to use aggregate statistics.


But in java or mongodb client (non-command line) to call mongodb, when using aggregate statistics, the results of statistics and count are also inaccurate. May I ask the Great Gods, my code is as follows, please ask the Great Gods for advice, and no reason can be found!

 public void testCount() throws Exception {
 DynamicSqlParameter dsp = new DynamicSqlParameter();
 long sT = System.currentTimeMillis();
 MongoDatasource mongoDatasource = MongoDatasource.getInstance(mongoService.getDatasource());
 DBCollection dbCollection = mongoDatasource.getDB().getCollection("dayFlow");
 List arrayList = new ArrayList<>();
 DBObject dbObject1 = new BasicDBObject();
 dbObject1.put("usedDayFlow", 2);
 DBObject dbObject2 = new BasicDBObject();
 dbObject2.put("_id", null);
 dbObject2.put("count", new BasicDBObject("$sum", 1));
 arrayList.add(new BasicDBObject("$match", dbObject1));
 arrayList.add(new BasicDBObject("$group", dbObject2));
 AggregationOutput size = dbCollection.aggregate(arrayList);
 System.out.println ("runtime:" plus ((system.currenttimemills ()-st)/1000) plus "s");

Results of implementation:

[ { “$match” : { “usedDayFlow” : 2}} , { “$group” : { “_id” : null , “count” : { “$sum” : 1}}}]

[{ “_id” : null , “count” : 1002223}]

This statistical result is a little more than the actual amount of data. Please ask the Great God how to operate the aggregation statistics for fragmented clusters.

This problem has been solved, using the latest driver mongo-java-driver-3.4.0. Through the following methods, the number of records can be accurately counted in the fragmented cluster mode. Thank you for your help!

mongo shell >> db.collection.aggregate([{$match:{categories:”Bakery”},{$group:{“_id”:null,”count”:{$sum:1}}}}])

public long getCount() {
 Strinuser = "user name";
 String database = "admin";
 String password = "password";
 MongoCredential credential = MongoCredential.createCredential(user,database, password.toCharArray());
 MongoClientOptions options = MongoClientOptions.builder()
 MongoClient MongoClient = New MongoClient (New Server Address ("IP Address", "Port"), Arrays. Aslist (Credential), Options);
 Get database ("database");
 MongoCollection < Document > Collection = MongoDatabase.getCollection ("Data Table");
 final long[] count = new long[1];
 Block<Document> printBlock = new Block<Document>() {
 public void apply(final Document document) {
 count[0] = (long) document.get("count");
 Bson bson = Filters.eq("categories", "Bakery");
 Aggregates.match(bson),, Accumulators.sum
 ("count", 1L))
 return count[0];