Skip to content

Commit c2994e9

Browse files
committed
Support update with aggregation pipeline in modify method
1 parent 4d3ab60 commit c2994e9

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

mongoengine/queryset/base.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -733,7 +733,15 @@ def modify(
733733
query["$where"] = where_clause
734734

735735
if not remove:
736-
update = transform.update(queryset._document, **update)
736+
if "__raw__" in update and isinstance(
737+
update["__raw__"], list
738+
): # Case of Update with Aggregation Pipeline
739+
update = [
740+
transform.update(queryset._document, **{"__raw__": u})
741+
for u in update["__raw__"]
742+
]
743+
else:
744+
update = transform.update(queryset._document, **update)
737745
sort = queryset._ordering
738746

739747
try:

tests/queryset/test_modify.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,35 @@ class BlogPost(Document):
130130
)
131131
assert blog.tags == ["python", "go", "rust", "code", "java"]
132132

133+
def test_modify_with_aggregation_update(self):
134+
"""Ensure that the 'aggregation_update' modify works correctly."""
135+
136+
class BlogPost(Document):
137+
slug = StringField()
138+
tags = ListField(StringField())
139+
140+
BlogPost.drop_collection()
141+
142+
post = BlogPost(slug="test")
143+
post.save()
144+
145+
BlogPost.objects(slug="test").update(
146+
__raw__=[{"$set": {"slug": {"$concat": ["$slug", " ", "$slug"]}}}],
147+
)
148+
post.reload()
149+
assert post.slug == "test test"
150+
151+
post = BlogPost.objects(slug="test test").modify(
152+
__raw__=[
153+
{"$set": {"slug": {"$concat": ["$slug", " ", "it"]}}}, # test test it
154+
{
155+
"$set": {"slug": {"$concat": ["When", " ", "$slug"]}}
156+
}, # When test test it
157+
],
158+
new=True,
159+
)
160+
assert post.slug == "When test test it"
161+
133162

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

0 commit comments

Comments
 (0)