標籤:clear ntb ase ntop timeout connect str new span
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 一個坑)