Skip to content

Commit

Permalink
Merge branch 'fix_none_queryset_run_on_all_collection' of github.com:…
Browse files Browse the repository at this point in the history
…idoshr/mongoengine into idoshr-fix_none_queryset_run_on_all_collection
  • Loading branch information
bagerard committed Feb 26, 2023
2 parents 042d7f2 + 28d7d65 commit 0767033
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
12 changes: 12 additions & 0 deletions mongoengine/queryset/base.py
Expand Up @@ -289,6 +289,9 @@ def create(self, **kwargs):
def first(self):
"""Retrieve the first object matching the query."""
queryset = self.clone()
if self._none or self._empty:
return None

try:
result = queryset[0]
except IndexError:
Expand Down Expand Up @@ -551,6 +554,8 @@ def update(

if write_concern is None:
write_concern = {}
if self._none or self._empty:
return 0

queryset = self.clone()
query = queryset._query
Expand Down Expand Up @@ -673,6 +678,9 @@ def modify(
if not update and not upsert and not remove:
raise OperationError("No update parameters, must either update or remove")

if self._none or self._empty:
return None

queryset = self.clone()
query = queryset._query
if not remove:
Expand Down Expand Up @@ -1306,6 +1314,10 @@ def aggregate(self, pipeline, *suppl_pipeline, **kwargs):
user_pipeline += suppl_pipeline

initial_pipeline = []
if self._none or self._empty:
initial_pipeline.append({"$limit": 1})
initial_pipeline.append({"$match": {"fldksjhkjhafds": "lasdjfhlasdhfk"}})

if self._query:
initial_pipeline.append({"$match": self._query})

Expand Down
13 changes: 13 additions & 0 deletions tests/queryset/test_queryset.py
Expand Up @@ -417,6 +417,19 @@ class A(Document):
A.drop_collection()
A().save()

# validate collection not empty
assert A.objects.count() == 1

# update operations
assert A.objects.none().update(s="1") == 0
assert A.objects.none().update_one(s="1") == 0
assert A.objects.none().modify(s="1") is None

# validate noting change by update operations
assert A.objects(s="1").count() == 0

# fetch queries
assert A.objects.none().first() is None
assert list(A.objects.none()) == []
assert list(A.objects.none().all()) == []
assert list(A.objects.none().limit(1)) == []
Expand Down
17 changes: 17 additions & 0 deletions tests/queryset/test_queryset_aggregation.py
Expand Up @@ -276,6 +276,23 @@ class Aggr(Document):
{"_id": agg2.id, "c": 0.0, "name": "Y"},
]

def test_queryset_aggregation_none(self):
class Person(Document):
name = StringField()
age = IntField()

Person.drop_collection()

p1 = Person(name="Isabella Luanna", age=16)
p2 = Person(name="Wilson Junior", age=21)
p3 = Person(name="Sandra Mara", age=37)
Person.objects.insert([p1, p2, p3])

pipeline = [{"$project": {"name": {"$toUpper": "$name"}}}]
data = Person.objects().none().order_by("name").aggregate(pipeline)

assert list(data) == []


if __name__ == "__main__":
unittest.main()

0 comments on commit 0767033

Please sign in to comment.