MCPcopy Index your code
hub / github.com/MongoEngine/mongoengine / count_documents

Function count_documents

mongoengine/pymongo_support.py:21–67  ·  view source on GitHub ↗

Pymongo>3.7 deprecates count in favour of count_documents

(
    collection, filter, skip=None, limit=None, hint=None, collation=None
)

Source from the content-addressed store, hash-verified

19
20
21def count_documents(
22 collection, filter, skip=None, limit=None, hint=None, collation=None
23):
24 """Pymongo>3.7 deprecates count in favour of count_documents"""
25 if limit == 0:
26 return 0 # Pymongo raises an OperationFailure if called with limit=0
27
28 kwargs = {}
29 if skip is not None:
30 kwargs["skip"] = skip
31 if limit is not None:
32 kwargs["limit"] = limit
33 if hint not in (-1, None):
34 kwargs["hint"] = hint
35 if collation is not None:
36 kwargs["collation"] = collation
37
38 # count_documents appeared in pymongo 3.7
39 if PYMONGO_VERSION >= (3, 7):
40 try:
41 if not filter and set(kwargs) <= {"max_time_ms"}:
42 # when no filter is provided, estimated_document_count
43 # is a lot faster as it uses the collection metadata
44 return collection.estimated_document_count(**kwargs)
45 else:
46 return collection.count_documents(filter=filter, **kwargs)
47 except OperationFailure as err:
48 if PYMONGO_VERSION >= (4,):
49 raise
50
51 # OperationFailure - accounts for some operators that used to work
52 # with .count but are no longer working with count_documents (i.e $geoNear, $near, and $nearSphere)
53 # fallback to deprecated Cursor.count
54 # Keeping this should be reevaluated the day pymongo removes .count entirely
55 if (
56 "$geoNear, $near, and $nearSphere are not allowed in this context"
57 not in str(err)
58 and "$where is not allowed in this context" not in str(err)
59 ):
60 raise
61
62 cursor = collection.find(filter)
63 for option, option_value in kwargs.items():
64 cursor_method = getattr(cursor, option)
65 cursor = cursor_method(option_value)
66 with_limit_and_skip = "skip" in kwargs or "limit" in kwargs
67 return cursor.count(with_limit_and_skip=with_limit_and_skip)
68
69
70def list_collection_names(db, include_system_collections=False):

Callers 4

_get_countMethod · 0.90
countMethod · 0.90
issue_1_count_queryMethod · 0.90
test_count_documentsMethod · 0.90

Calls 2

itemsMethod · 0.80
countMethod · 0.45

Tested by 2

issue_1_count_queryMethod · 0.72
test_count_documentsMethod · 0.72