2
Bson filter = Filters.and(Filters.eq("appId", appId),
                        Filters.eq("ch", ch.getCh()),
                        Filters.gte("updateTime", startSeconds)
                );
long c = mainCollection.count(filter);  //run ok quickly, but it is Deprecated
// long c = mainCollection.countDocuments(filter);  socketTimeout

Java use MongoCollection.countDocuments() executes slowly or even times out, but the deprecated count() method is ok.

prasad_
  • 12,755
  • 2
  • 24
  • 36
夏申洋
  • 21
  • 3
  • You mean `countDocuments` _not_ `countCollections()`? Please update the post with correct information. – prasad_ Mar 04 '20 at 06:35
  • Oh, Sorry. Yes, when I use `countDocuments` to count the document number encountered socket timeout exception. But I use mongodb command `db.collection.find({...}).count()` perform well – 夏申洋 Mar 05 '20 at 02:01
  • Are there any indexes defined on the fields used in the _filter_ (`appId`, ...)? – prasad_ Mar 05 '20 at 04:16
  • Yes, the index of `(appId, ch, updateTime)` has been established, so use command for query the count quickly. – 夏申洋 Mar 06 '20 at 07:55
  • Does the `countDocuments` run faster? – prasad_ Mar 06 '20 at 08:00
  • And I found the `Collection.countDocuments()` use the `executeCount(clientSession, filter, options, CountStrategy.AGGREGATE)`, but the `Collection.count()` use the `executeCount(clientSession, filter, options, CountStrategy.COMMAND)` – 夏申洋 Mar 06 '20 at 08:02
  • `countDocuments()` run slowly, and socketTimeout exception – 夏申洋 Mar 06 '20 at 08:04
  • Please run the `explain("executionStats")` on the `countDocuments()` and post the details. – prasad_ Mar 06 '20 at 08:33
  • Oh, you mean use the command to run these? Sry, I am unfamiliar with how to perform these two methods together using Java collection. – 夏申洋 Mar 06 '20 at 08:43
  • Looks like you cannot run `explain` on `countDocuments`. – prasad_ Mar 06 '20 at 10:23

1 Answers1

0

MongoCollection.estimatedDocumentCount() and MongoCollection.count() in the legacy API both use the collection's metadata to provide the size of the collection. Compared to MongoCollection.countDocuments(), which performs a full collection scan, they are much faster, but cannot accept filters.

The specifics of the deprecated MongoCollection.count() vs .estimatedDocumentCount() appears to be a consistency issue within transactions, and clarifying that the method may not be 100% accurate.

See the Java usage examples or shell documentation for a similar explanation.