mongodb count 導致不正確的數量(mongodb count 一個坑)
阿新 • • 發佈:2018-02-08
ride getc 官網 foreach arrays 圖片 client tab tor
https://www.cnblogs.com/Kellana/p/5844919.html
在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]; }
mongodb count 導致不正確的數量(mongodb count 一個坑)