Https://www.cnblogs.com/Kellana/p/5844919.html
In a MongoDB cluster, if exists orphaned documents and chunk migration, the count query may result in an incorrect query result, such as I was stepping on the pit, first not talking, see the result:
Skip can only get to 54631, and count found out 77,396 data, this is the pit, the same query conditions, not the same results, in order to avoid this result, you can use the aggregate query,
As shown, the inside is a pit.
For more information on the count of MongoDB, see official website: https://docs.mongodb.com/manual/reference/command/count/
https://segmentfault.com/q/1010000008787002
The problem has been resolved, using the latest driver mongo-java-driver-3.4.0, through the following method can be in the Shard cluster mode, accurate statistics to the number of records, thank you for your help! MONGO Shell >> db.collection.aggregate ([{$match: {categories: "Bakery"},{$group: {"_id": null, "Count": {$sum: 1}} }}])
Public LongGetCount () {String user="User name"; String Database="Admin"; String Password="Password"; Mongocredential Credential=mongocredential.createcredential (User,database, Password.tochararray ()); Mongoclientoptions Options=Mongoclientoptions.builder (). Connectionsperhost (Ten). Threadsallowedtoblockforconnectionmultiplier (Ten). Sockettimeout (20000). ConnectTimeout (15000). Maxwaittime (50000). build (); Mongoclient mongoclient=NewMongoclient (NewServerAddress ("IP Address","Port"), Arrays.aslist (credential), options); Mongodatabase Mongodatabase= Mongoclient.getdatabase ("Database"); Mongocollection<Document> collection = Mongodatabase.getcollection ("Data Sheet"); FinalLong[] Count =New Long[1]; Block<Document> Printblock =NewBlock<document>() {@Override Public voidApply (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); returncount[0];}
MongoDB count results in incorrect number (MongoDB count a pit)