@@ -37,7 +37,12 @@ def count_documents(
3737 # count_documents appeared in pymongo 3.7
3838 if PYMONGO_VERSION >= (3 , 7 ):
3939 try :
40- return collection .count_documents (filter = filter , ** kwargs )
40+ if not filter and set (kwargs ) <= {"max_time_ms" }:
41+ # when no filter is provided, estimated_document_count
42+ # is a lot faster as it uses the collection metadata
43+ return collection .estimated_document_count (** kwargs )
44+ else :
45+ return collection .count_documents (filter = filter , ** kwargs )
4146 except OperationFailure as err :
4247 if PYMONGO_VERSION >= (4 ,):
4348 raise
@@ -46,15 +51,10 @@ def count_documents(
4651 # with .count but are no longer working with count_documents (i.e $geoNear, $near, and $nearSphere)
4752 # fallback to deprecated Cursor.count
4853 # Keeping this should be reevaluated the day pymongo removes .count entirely
49- message = str (err )
50- if not (
51- "not allowed in this context" in message
52- and (
53- "$where" in message
54- or "$geoNear" in message
55- or "$near" in message
56- or "$nearSphere" in message
57- )
54+ if (
55+ "$geoNear, $near, and $nearSphere are not allowed in this context"
56+ not in str (err )
57+ and "$where is not allowed in this context" not in str (err )
5858 ):
5959 raise
6060
0 commit comments