Skip to content

Commit

Permalink
Use estimated_documents_count OR documents_count based on query
Browse files Browse the repository at this point in the history
  • Loading branch information
bagerard committed Jun 6, 2021
1 parent cc85165 commit 5b53314
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 112 deletions.
108 changes: 0 additions & 108 deletions .travis_.yml

This file was deleted.

16 changes: 13 additions & 3 deletions mongoengine/pymongo_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,23 @@ def count_documents(
# count_documents appeared in pymongo 3.7
if IS_PYMONGO_GTE_37:
try:
return collection.count_documents(filter=filter, **kwargs)
except OperationFailure:
if not filter and set(kwargs) <= {"max_time_ms"}:
# when no filter is provided, estimated_document_count
# is a lot faster as it uses the collection metadata
return collection.estimated_document_count(**kwargs)
else:
return collection.count_documents(filter=filter, **kwargs)
except OperationFailure as exc:
# OperationFailure - accounts for some operators that used to work
# with .count but are no longer working with count_documents (i.e $geoNear, $near, and $nearSphere)
# fallback to deprecated Cursor.count
# Keeping this should be reevaluated the day pymongo removes .count entirely
pass
if (
"$geoNear, $near, and $nearSphere are not allowed in this context"
not in str(exc)
and "$where is not allowed in this context" not in str(exc)
):
raise

cursor = collection.find(filter)
for option, option_value in kwargs.items():
Expand Down
3 changes: 2 additions & 1 deletion tests/test_context_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
switch_db,
)
from mongoengine.pymongo_support import count_documents
from tests.utils import MongoDBTestCase


class TestContextManagers:
class TestContextManagers(MongoDBTestCase):
def test_set_write_concern(self):
connect("mongoenginetest")

Expand Down

0 comments on commit 5b53314

Please sign in to comment.