在mongodb 集群中,if 存在orphaned documents 和chunk migration, count查询可能会导致一个不正确的查询结果,例如我就是踩的这个坑,先不说话,看结果:
skip 只能获取到54631,而count查出来了77396条数据,这就是坑,一样的查询条件,不一样的结果,为了避免这种结果,可以使用聚合查询,
如上图所示,着里又是一个坑。
mongodb 的count详细文档见官网:https://docs.mongodb.com/manual/reference/command/count/
https://segmentfault.com/q/1010000008787002
该问题已经解决,使用的是最新驱动mongo-java-driver-3.4.0,通过下面的方法可以在分片集群模式下,准确的统计到记录数量,感谢大家的相助!
mongo shell >> db.collection.aggregate([{$match:{categories:"Bakery"},{$group:{"_id":null,"count":{$sum:1}}}}])
public long getCount() { String user = "用户名"; String database = "admin"; String password = "密码"; MongoCredential credential = MongoCredential.createCredential(user,database, password.toCharArray()); MongoClientOptions options = MongoClientOptions.builder() .connectionsPerHost(10) .threadsAllowedToBlockForConnectionMultiplier(10) .socketTimeout(20000) .connectTimeout(15000) .maxWaitTime(50000) .build(); MongoClient mongoClient = new MongoClient(new ServerAddress("IP地址", "端口"), Arrays.asList(credential), options); MongoDatabase mongoDatabase = mongoClient.getDatabase("数据库"); MongoCollection<Document> collection = mongoDatabase.getCollection("数据表"); final long[] count = new long[1]; Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { count[0] = (long) document.get("count"); } }; Bson bson = Filters.eq("categories", "Bakery"); collection.aggregate( Arrays.asList( Aggregates.match(bson), Aggregates.group(null, Accumulators.sum ("count", 1L)) ) ).forEach(printBlock); return count[0]; }
正确的count方式:
db.xxx.find( { timeUpdated : {\\$gte: 1517414400000 , \\$lt: 1517587200000 } } ).count()
db.xxx.find( { timeUpdated : {\\$gte: NumberLong("1517500800000") , \\$lt: NumberLong("1517587200000") } } ).count()