在mongodb分片集群下,直接用count统计会不准确,用聚合统计则可以
但是在java或mongodb客户端(非命令行)调用mongodb,使用聚合统计时,统计的结果和count同样不准确,请问大神们,我的代码如下,请大神指点,找不到原因!
@Test
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));
System.out.println(JSON.serialize(arrayList));
AggregationOutput size = dbCollection.aggregate(arrayList);
System.out.println(size.results());
System.out.println("运行时间:" + ((System.currentTimeMillis() - sT) /1000) + "s");
}
执行结果:
[ { "$match" : { "usedDayFlow" : 2}} , { "$group" : { "_id" : null , "count" : { "$sum" : 1}}}]
[{ "_id" : null , "count" : 1002223}]
该问题已经解决,使用的是最新驱动mongo-java-driver-3.4.0,通过下面的方法可以在分片集群模式下,准确的统计到记录数量,感谢大家的相助!
mongo shell >> db.collection.aggregate([{$match:{categories:"Bakery"},{$group:{"_id":null,"count":{$sum:1}}}}])